using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using ComponentPro;
using ComponentPro.Net.Mail;

namespace Samples
{
    public partial class OrderInvoice : Form
    {
        private bool _exception;

        public OrderInvoice()
        {
            try
            {
                InitializeComponent();                
            }
            catch (ComponentPro.Licensing.TemplateEngine.UltimateLicenseException exc)
            {
                MessageBox.Show(exc.Message);
                _exception = true;
                return;
            }

            cbxSec.SelectedIndex = 0;
            cbxMethod.SelectedIndex = 0;
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (_exception)
                this.Close();
        }

        class OrderProduct
        {
            private int _partId;
            private string _productName;
            private int _quantity;
            private float _price;

            public int PartId
            {
                get { return _partId; }
                set { _partId = value; }
            }

            public string ProductName
            {
                get { return _productName; }
                set { _productName = value; }
            }

            public int Quantity
            {
                get { return _quantity; }
                set { _quantity = value; }
            }

            public float Price
            {
                get { return _price; }
                set { _price = value; }
            }
        }

        /// <summary>
        /// This class will be used as a data source of the email template to personalize an email content.
        /// </summary>
        class User
        {
            private string _fullName;
            private string _emailAddress;
            private string _password;

            /// <summary>
            /// Gets the full name of the customer.
            /// </summary>
            public string FullName
            {
                get { return _fullName; }
                set { _fullName = value; }
            }

            /// <summary>
            /// Gets the email address of the customer.
            /// </summary>
            public string EmailAddress
            {
                get { return _emailAddress; }
                set { _emailAddress = value; }
            }

            /// <summary>
            /// Gets the password to login of the customer.
            /// </summary>
            public string Password
            {
                get { return _password; }
                set { _password = value; }
            }

            /// <summary>
            /// Returns a list of purchased products.
            /// </summary>
            /// <returns>The purchased products.</returns>
            public OrderProduct[] GetOrders()
            {
                // Assume that this customer has purchased three products.
                OrderProduct[] ops = new OrderProduct[3];

                ops[0] = new OrderProduct();
                ops[0].PartId = 1239;
                ops[0].Price = 104.09f;
                ops[0].ProductName = "Product A";
                ops[0].Quantity = 3;

                ops[1] = new OrderProduct();
                ops[1].PartId = 22;
                ops[1].Price = 134.09f;
                ops[1].ProductName = "Product B";
                ops[1].Quantity = 1;

                ops[2] = new OrderProduct();
                ops[2].PartId = 167;
                ops[2].Price = 14.7f;
                ops[2].ProductName = "Product C";
                ops[2].Quantity = 5;

                return ops;
            }
        }

        /// <summary>
        /// Personalizes email subject and body.
        /// </summary>
        /// <param name="subject">The email subject template.</param>
        /// <param name="body">The email body template</param>
        private void Generate(ref string subject, ref string body)
        {
            // Load subject template.
            dt.LoadFromString(txtSubject.Text);

            // Create a user defined object.
            User u = new User();
            // Set some information.
            u.EmailAddress = "myemail@somedomain.com";
            u.FullName = "John Borders";
            u.Password = "123abc";

            // Assign variables.
            dt.SetValue("CompanyName", "My Company Name");
            dt.SetValue("User", u);
            dt.SetValue("OrderId", "1625DGHJ");

            // Personalize email's subject.
            subject = dt.Run();

            // Load content template.
            dt.LoadFromString(txtSource.Text);
            
            // Personalize email's body.            
            body = dt.Run();
        }

        /// <summary>
        /// Handles the Preview button's Click event.
        /// </summary>
        /// <param name="sender">The button object.</param>
        /// <param name="e">The event arguments.</param>
        private void btnPreview_Click(object sender, EventArgs e)
        {
            try
            {
                string subject = null;
                string content = null;

                // Personalize email subject and content.
                Generate(ref subject, ref content);
                // Show them.
                txtSubjectGen.Text = subject;
                txtOutput.Text = content;
            }
            catch (Exception exc)
            {
                MessageBox.Show("An error occurred: " + exc.Message);
            }
        }

        /// <summary>
        /// Handles the send menu item's Click event.
        /// </summary>
        /// <param name="sender">The menu item.</param>
        /// <param name="e">The event arguments.</param>
        private void sendToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                int port;
                try
                {
                    // Parse and validate SMTP port number.
                    port = int.Parse(txtPort.Text);
                    if (port < 1 || port > 65535)
                    {
                        MessageBox.Show("Invalid port, port must be from 1->65535", "Error");
                        return;
                    }
                }
                catch (FormatException)
                {
                    MessageBox.Show("Invalid port, port must be from 1->65535", "Error");
                    return;
                }

                if (txtFrom.Text.Length == 0)
                {
                    MessageBox.Show("Please enter From email", "Error");
                    return;
                }

                if (txtServer.Text.Length == 0)
                {
                    MessageBox.Show("Please enter server address", "Error");
                    return;
                }

                if (txtTo.Text.Length == 0)
                {
                    MessageBox.Show("Please enter recipient(s)", "Error");
                    return;
                }

                if (txtSubject.Text.Length == 0)
                {
                    MessageBox.Show("Please enter subject", "Error");
                    return;
                }

                if (txtSource.Text.Length == 0)
                {
                    MessageBox.Show("Please enter body", "Error");
                    return;
                }

                // Create a new mail object.
                MailMessage mail = new MailMessage();
                string subject = null, content = null;
                // Personalize subject and content.
                Generate(ref subject, ref content);
                // Build the message.
                mail.Subject = subject;
                mail.BodyHtml = content;
                mail.From.Add(txtFrom.Text);
                mail.To.Add(txtTo.Text);
                mail.Cc.Add(txtCC.Text);

                // Connect to the Smtp server.
                smtpClient.Connect(txtServer.Text, port, (ComponentPro.Net.SecurityMode)cbxSec.SelectedIndex);
                if (txtUserName.Text.Trim().Length > 0)
                    // Login with the user name and password provided.
                    smtpClient.Authenticate(txtUserName.Text, txtPassword.Text, (SmtpAuthenticationMethod)cbxMethod.SelectedIndex);
                // Send generated mail.
                smtpClient.Send(mail);

                MessageBox.Show("Message has been sent successfully!", "Message Sent", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception exc)
            {
                MessageBox.Show("An error occurred: " + exc.Message);
            }
            finally
            {
                // Close the connection.
                smtpClient.Disconnect();
            }
        }

        /// <summary>
        /// Handles the Send button's Click event.
        /// </summary>
        /// <param name="sender">The menu item.</param>
        /// <param name="e">The event arguments.</param>
        private void btnSend_Click(object sender, EventArgs e)
        {
            sendToolStripMenuItem_Click(null, null);
        }
    }
}