using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Mail;
using System.Net.Security;
using System.Web.UI;
using System.Security.Cryptography.X509Certificates;

namespace pmsDataGridView
{
    class AutoEmail
    {
        #region Constructor and Distructor
        public AutoEmail(SaleRecord sale, Customer customer)
        {
            this.sale = sale;
            this.customer = customer;
        }

        #endregion

        public int send(MainForm.EmailType emailtype)
        {// if everything gone thro well, returns 0

            //int selected_row_index = sale_index;
            //int ci = salelist[sale_index].CustomerIndex;            
            string to = customer.Email;
            string subject = null;
            string body = null;
            int returnflag = 0;

            

            ProductList bl = sale.BearingOrder;
            StringWriter writer = new StringWriter();
            HtmlTextWriter html = new HtmlTextWriter(writer);
            //if can't find the email config txt file, create a blank file and return
            if (File.Exists(email_account_path) == false || File.Exists(purchase_confirmation_path) == false
                || File.Exists(delivery_confirmation_path) == false)
            {
                return 2;
            }
            
            //read the email account text file
            if (read_email_account_txt_file() == 3) { return 3; };
            
            //read purchase confirmation text file
            if (read_purchase_confirmation_txt_file() == 3) { return 3; };

            if (read_delivery_confirmation_txt_file() == 3) { return 3; };

            if (read_signature_txt_file() == 3) { return 3; };
            //if (InitConfig.Business == InitConfig.BusinessType.BEARING)
            //{
            //    //display in email as "sender"
            //    SenderDisplayName = "NZ Miniature Bearings";
            //}
            //else if (InitConfig.Business == InitConfig.BusinessType.ELECTRONICS)
            //{
            //    //display in email as "sender"
            //    SenderDisplayName = "Hobbyist";
            //}

            System.Text.StringBuilder EmailBody = new System.Text.StringBuilder();
            html.RenderBeginTag(HtmlTextWriterTag.Html);
            html.Write("Dear " + customer.Name + "<br><br>");

            if (emailtype == MainForm.EmailType.PURCHASE)
            {
                //note: not for pick ups
                subject = purchase_confirmation_subject + " " + sale.ID;
                if (sale.Paid)
                {
                    body = purchase_confirmation_body_paid;
                }
                else
                {
                    body = purchase_confirmation_body_unpaid;
                }
    //                subject = "Purchase confirmation";
    //                body = "Thank you so much for buying from us. Below is your purchase information. " +
    //"Please let us know asap if the purchased items or the address is incorrect, otherwise the items will be sent off within a couple of days. " +
    //"You will receive an email notice once the items are packed. " +
    //"Payment can be made through bank deposit or Paypal." +
    //"<br><br>" +
    //"Bank deposit:<br>" +
    //"Please pay to the Westpac bank account 03 0830 0640509 000 using your name as reference. We prefer electronic deposit as it has no additional fees. For manual or cash deposit in a bank, please add $3 to the final amount to cover the bank fee. " +
    //"<br><br>" +
    //"Paypal:<br>" +
    //"Payment may be made via Paypal to this email account. Please log into your Paypal account and go to the \"Send money\" tab to complete the transaction. " +
    //"<br><br>" +
    //"We really appreciate your time for making the payment. <br><br>";
                

    //            else if (InitConfig.Business == InitConfig.BusinessType.ELECTRONICS)
    //            {
    //                //note: not for pick ups
    //                subject = "Purchase confirmation";
    //                body = "Thank you so much for buying from us. Below is your purchase information. " +
    //"Please let us know asap if the purchased items or the address is incorrect. " + 
    //"Otherwise the item(s) will be packed with Standard Post tracked within the next couple of days. " +
    //"You will receive an email notice once the item is packed. " +
    //"If you haven't made payment through a credit card or other means, please deposit payment (including shipping) " +
    //"to the ANZ bank account 01 0819 0420708 00 using your name or Trade me auction no. as reference." +
    //"<br><br>";                          
    //            }
            }
            else if (emailtype == MainForm.EmailType.SENT)
            {
                subject = delivery_confirmation_subject + " " + sale.ID;
                body = delivery_confirmation_body;
                //if (InitConfig.Business == InitConfig.BusinessType.BEARING)
                //{
                //    subject = "Delivery confirmation";
                //    body = "We are pleased to inform you that the following items have been posted. Thank you so much " +
                //"for the purchase, we look forward to working with you again.<br><br>";
                //}
                //else if (InitConfig.Business == InitConfig.BusinessType.ELECTRONICS)
                //{
                //    subject = "Delivery confirmation";
                //    body = "We are pleased to inform you that the following items have been posted. Thank you so much " +
                //"for the purchase, we look forward to working with you again. " +
                ////"<br><br>" +
                ////"You are also eligible for Free shipping on any other purchase from our site, <a href=\"http://www.hobbyist.co.nz\">www.hobbyist.co.nz</a>. " +
                ////"Please quote this key <b>cust0096</b> when you make the next order to avail free shipping. The code expires 3 months after the day you receive this email. <br><br>" +
                //"Hope you have fun building your project. Let us know if you have any technical queries, we would be glad to answer.<br><br>";
                //}
            }
            html.Write(body);

            if (InitConfig.Business == InitConfig.BusinessType.BEARING)
            {
                //start the table
                html.RenderBeginTag(HtmlTextWriterTag.Style);//3
                html.Write("td {padding-right: 10px;}");
                html.RenderEndTag();//3
                html.RenderEndTag();
                html.AddAttribute("border", "1");
                html.RenderBeginTag(HtmlTextWriterTag.Table);//1
                html.RenderBeginTag(HtmlTextWriterTag.Tr);//2
                html.RenderBeginTag(HtmlTextWriterTag.Th);//3
                html.Write("Part #");
                html.RenderEndTag();//3
                html.RenderBeginTag(HtmlTextWriterTag.Th);//3
                html.Write("Item");
                html.RenderEndTag();//3
                html.RenderBeginTag(HtmlTextWriterTag.Th);//3
                html.Write("Code");
                html.RenderEndTag();//3
                /*
                html.RenderBeginTag(HtmlTextWriterTag.Th);//3
                html.Write("Brand");
                html.RenderEndTag();//3
                 * */
                html.RenderBeginTag(HtmlTextWriterTag.Th);//3
                html.Write("Qty");
                html.RenderEndTag();//3
                html.RenderBeginTag(HtmlTextWriterTag.Th);//3
                html.Write("Each");
                html.RenderEndTag();//3
                html.RenderBeginTag(HtmlTextWriterTag.Th);//3
                html.Write("Total");
                html.RenderEndTag();//3
                html.RenderEndTag();//2
                for (int i = 0; i < bl.Count; i++)
                {
                    double subtotal = bl[i].quantity * bl[i].Price;
                    string nameLink;

                    html.RenderBeginTag(HtmlTextWriterTag.Tr);//2
                    html.RenderBeginTag(HtmlTextWriterTag.Td);//part number
                    html.Write(bl[i].ID);
                    html.RenderEndTag();
                    html.RenderBeginTag(HtmlTextWriterTag.Td);//name
                    if (bl[i].ourLink == null)
                    {
                        html.Write(bl[i].name);
                    }
                    else
                    {
                        nameLink = "<a href=\"" + bl[i].ourLink + "\">" + bl[i].name + "</a>";
                        html.Write(nameLink);
                    } 
                    //html.Write(bl[i].name);
                    html.RenderEndTag();
                    html.RenderBeginTag(HtmlTextWriterTag.Td);//code
                    html.Write(bl[i].Code);
                    html.RenderEndTag();
                    /*
                    html.RenderBeginTag(HtmlTextWriterTag.Td);//brand
                    html.Write(bl[i].Brand.ToString());
                    html.RenderEndTag();
                    */
                    html.RenderBeginTag(HtmlTextWriterTag.Td);//quantity
                    html.Write(bl[i].quantity.ToString());
                    html.RenderEndTag();
                    html.RenderBeginTag(HtmlTextWriterTag.Td);//each
                    html.Write(bl[i].Price.ToString("$0.00"));
                    html.RenderEndTag();
                    html.RenderBeginTag(HtmlTextWriterTag.Td);//total
                    html.Write(subtotal.ToString("$0.00"));
                    html.RenderEndTag();
                    html.RenderEndTag();
                }
                html.RenderBeginTag(HtmlTextWriterTag.Tr);

                //print out discount row if there is any
                if (sale.Discount != 0)
                {
                    double discount_amount = (sale.Payable - sale.ShippingPayable) * (1 - 1 / (1 - sale.Discount * 0.01));//note, payable is already the discounted figure
                    html.RenderBeginTag(HtmlTextWriterTag.Tr);
                    html.RenderBeginTag(HtmlTextWriterTag.Td);//Discount
                    html.Write("Discount");
                    html.RenderEndTag();
                    //produce 3 horizontal space
                    for (int i = 0; i < 3; i++)
                    {
                        html.RenderBeginTag(HtmlTextWriterTag.Td);//space
                        html.Write("-");
                        html.RenderEndTag();
                    }
                    html.RenderBeginTag(HtmlTextWriterTag.Td);//percentage
                    html.Write(sale.Discount.ToString() + "%");
                    html.RenderEndTag();
                    html.RenderBeginTag(HtmlTextWriterTag.Td);//amount
                    html.Write(discount_amount.ToString("$0.00"));
                    html.RenderEndTag();
                    html.RenderEndTag();
                }

                //print out shipping row
                html.RenderBeginTag(HtmlTextWriterTag.Td);//shipping
                html.Write("Shipping");
                html.RenderEndTag();
                //produce 4 horizontal space
                for (int i = 0; i < 4; i++)
                {
                    html.RenderBeginTag(HtmlTextWriterTag.Td);//space
                    html.Write("-");
                    html.RenderEndTag();
                }
                html.RenderBeginTag(HtmlTextWriterTag.Td);//shipping cost
                html.Write(sale.ShippingPayable.ToString("$0.00"));
                html.RenderEndTag();
                html.RenderEndTag();

                //print out total row
                html.RenderBeginTag(HtmlTextWriterTag.Tr);
                html.RenderBeginTag(HtmlTextWriterTag.Td);//total
                html.Write("Total");
                html.RenderEndTag();
                //produce 2 horizontal space
                for (int i = 0; i < 2; i++)
                {
                    html.RenderBeginTag(HtmlTextWriterTag.Td);//space
                    html.Write("-");
                    html.RenderEndTag();
                }
                html.RenderBeginTag(HtmlTextWriterTag.Td);//total
                html.Write(sale.BearingOrder.TotalNumberOfBearings.ToString());
                html.RenderEndTag();
                //produce 1 horizontal space
                html.RenderBeginTag(HtmlTextWriterTag.Td);//space
                html.Write("-");
                html.RenderEndTag();

                html.RenderBeginTag(HtmlTextWriterTag.Td);//amount
                html.Write(sale.Payable.ToString("$0.00"));
                html.RenderEndTag();
                html.RenderEndTag();

                html.RenderEndTag();//end table 

                html.Write("<br>");
                //EmailBody.Append("<br>Total\t" + sale.BearingOrder.TotalNumberOfBearings.ToString() + "\t\t" + sale.Payable.ToString("$0.00"));
                //EmailBody.Append(Environment.NewLine + Environment.NewLine);

                //print out address    
                //html.Write("Delivery address:<br>");
                //html.Write(customer.Name + "<br>");
                //string[] splited_address_lines = customer.Address.Split('\n');

                //foreach (string addressline in splited_address_lines)
                //{
                //    html.Write(addressline + "<br>");
                //}
                //html.Write(customer.Country + "<br><br><br>");
                //html.Write("Yours sincerely<br>");
                //html.Write("King Au<br>" + "021 025 375 22<br>" + "NZ Miniature Bearings<br>");
                //html.Write("<a href=\"http://www.nzminiaturebearings.com\">www.nzminiaturebearings.com</a>");
                //html.Write("www.nzminiaturebearings.com<br>");

            }

            else if (InitConfig.Business == InitConfig.BusinessType.ELECTRONICS)
            {
                //start the table
                html.RenderBeginTag(HtmlTextWriterTag.Style);//3
                html.Write("td {padding-right: 10px;}");
                html.RenderEndTag();//3
                html.RenderEndTag();
                html.AddAttribute("border", "1");
                html.RenderBeginTag(HtmlTextWriterTag.Table);//1
                html.RenderBeginTag(HtmlTextWriterTag.Tr);//2
                html.RenderBeginTag(HtmlTextWriterTag.Th);//3
                html.Write("Item");
                html.RenderEndTag();//3
                html.RenderBeginTag(HtmlTextWriterTag.Th);//3
                html.Write("Description");
                html.RenderEndTag();//3
                html.RenderBeginTag(HtmlTextWriterTag.Th);//3
                html.Write("Qty");
                html.RenderEndTag();//3
                html.RenderBeginTag(HtmlTextWriterTag.Th);//3
                html.Write("Each");
                html.RenderEndTag();//3
                html.RenderBeginTag(HtmlTextWriterTag.Th);//3
                html.Write("Total");
                html.RenderEndTag();//3
                html.RenderEndTag();//2
                for (int i = 0; i < bl.Count; i++)
                {
                    double subtotal = bl[i].quantity * bl[i].Price;
                    string nameLink;

                    html.RenderBeginTag(HtmlTextWriterTag.Tr);//2
                    html.RenderBeginTag(HtmlTextWriterTag.Td);//name
                    if (bl[i].ourLink == null)
                    {
                        html.Write(bl[i].name);
                    }
                    else
                    {
                        nameLink = "<a href=\"" + bl[i].ourLink + "\">" + bl[i].name + "</a>";
                        html.Write(nameLink);
                    }                    
                    //<a href=\"http://www.hobbyist.co.nz\">www.hobbyist.co.nz</a>
                    html.RenderEndTag();
                    html.RenderBeginTag(HtmlTextWriterTag.Td);//Description
                    if (bl[i].Desription == null)
                    {
                        html.Write("-");
                    }
                    else
                    {
                        html.Write(bl[i].Desription);
                    }
                    html.RenderEndTag();
                    html.RenderBeginTag(HtmlTextWriterTag.Td);//quantity
                    html.Write(bl[i].quantity.ToString());
                    html.RenderEndTag();
                    html.RenderBeginTag(HtmlTextWriterTag.Td);//each
                    html.Write(bl[i].Price.ToString("$0.00"));
                    html.RenderEndTag();
                    html.RenderBeginTag(HtmlTextWriterTag.Td);//total
                    html.Write(subtotal.ToString("$0.00"));
                    html.RenderEndTag();
                    html.RenderEndTag();
                }
                html.RenderBeginTag(HtmlTextWriterTag.Tr);

                //print out discount row if there is any
                if (sale.Discount != 0)
                {
                    double discount_amount = (sale.Payable - sale.ShippingPayable) * (1 - 1 / (1 - sale.Discount * 0.01));//note, payable is already the discounted figure
                    html.RenderBeginTag(HtmlTextWriterTag.Tr);
                    html.RenderBeginTag(HtmlTextWriterTag.Td);//Discount
                    html.Write("Discount");
                    html.RenderEndTag();
                    //produce 2 horizontal space
                    for (int i = 0; i < 2; i++)
                    {
                        html.RenderBeginTag(HtmlTextWriterTag.Td);//space
                        html.Write("-");
                        html.RenderEndTag();
                    }
                    html.RenderBeginTag(HtmlTextWriterTag.Td);//percentage
                    html.Write(sale.Discount.ToString() + "%");
                    html.RenderEndTag();
                    html.RenderBeginTag(HtmlTextWriterTag.Td);//amount
                    html.Write(discount_amount.ToString("$0.00"));
                    html.RenderEndTag();
                    html.RenderEndTag();
                }

                //print out shipping row
                html.RenderBeginTag(HtmlTextWriterTag.Td);//shipping
                html.Write("Shipping");
                html.RenderEndTag();
                //produce 2 horizontal space
                for (int i = 0; i < 3; i++)
                {
                    html.RenderBeginTag(HtmlTextWriterTag.Td);//space
                    html.Write("-");
                    html.RenderEndTag();
                }
                html.RenderBeginTag(HtmlTextWriterTag.Td);//shipping cost
                html.Write(sale.ShippingPayable.ToString("$0.00"));
                html.RenderEndTag();
                html.RenderEndTag();

                //print out total row
                html.RenderBeginTag(HtmlTextWriterTag.Tr);
                html.RenderBeginTag(HtmlTextWriterTag.Td);//total
                html.Write("Total");
                html.RenderEndTag();
                //produce 1 horizontal space
                for (int i = 0; i < 1; i++)
                {
                    html.RenderBeginTag(HtmlTextWriterTag.Td);//space
                    html.Write("-");
                    html.RenderEndTag();
                }
                html.RenderBeginTag(HtmlTextWriterTag.Td);//total
                html.Write(sale.BearingOrder.TotalNumberOfBearings.ToString());
                html.RenderEndTag();
                //produce 1 horizontal space
                html.RenderBeginTag(HtmlTextWriterTag.Td);//space
                html.Write("-");
                html.RenderEndTag();

                html.RenderBeginTag(HtmlTextWriterTag.Td);//amount
                html.Write(sale.Payable.ToString("$0.00"));
                html.RenderEndTag();
                html.RenderEndTag();

                html.RenderEndTag();//end table 

                html.Write("<br>");                 
            }
            //print out address    
            html.Write("Delivery address:<br>");
            html.Write(customer.Name + "<br>");
            string[] splited_address_lines = customer.Address.Split('\n');

            foreach (string addressline in splited_address_lines)
            {
                html.Write(addressline + "<br>");
            }
            html.Write(customer.Country + "<br>");

            //if it's courier tracked, then send out the tracking url 
            if (sale.trackingNumber != null)
            {
                string trackingInfo;
                trackingInfo = "<br>You can check the status of your package by the link below. Please allow up to 12 hours for the Courier to pick up the parcel and make the tracking status available online. <br> <a href=\"http://trackandtrace.courierpost.co.nz/search/" + sale.trackingNumber + "\">http://trackandtrace.courierpost.co.nz/search/" + sale.trackingNumber+"</a><br>";
                html.Write(trackingInfo);            
            }
            html.Write("<br><br>");
            html.Write(Signature);

            try
            {
                System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
                System.Net.NetworkCredential cred = new System.Net.NetworkCredential(EmailAccount, Password);
                mail.To.Add(to);
                mail.Subject = subject;
                mail.From = new System.Net.Mail.MailAddress(EmailAccount, SenderDisplayName);
                mail.IsBodyHtml = true;                    
                mail.Body = writer.ToString();
                System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(smtpServer);
                smtp.UseDefaultCredentials = false;
                smtp.EnableSsl = true;
                smtp.Credentials = /*new System.Net.NetworkCredential("contact@hobbyist.co.nz", "DreamBig");*/cred;
                smtp.Port = Convert.ToInt32(smtpPort);
				ServicePointManager.ServerCertificateValidationCallback = 
                delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) 
                    { return true; };
                smtp.Send(mail);
                return 0;
            }
            catch (Exception ex)
            {
				this.Logger("Error Email"+ ex.Message);
                return 1;
            }
        }
		public void Logger(String lines)
{

 // Write the string to a file.append mode is enabled so that the log
 // lines get appended to  test.txt than wiping content and writing the log

  System.IO.StreamWriter file = new System.IO.StreamWriter("/tmp/test.txt",true);
  file.WriteLine(lines);

  file.Close();

}
        int read_email_account_txt_file()
        {
            //read email details from email_account.txt file
            try
            {
                // Create an instance of StreamReader to read from a file.
                // The using statement also closes the StreamReader.
                using (StreamReader sr = new StreamReader(email_account_path))
                {
                    String line;
                    //igure the lines begin with %
                    //.CompareTo
                    //Less than zero: This instance precedes value. 
                    //Zero: This instance has the same position in the sort order as value.
                    //Greater than zero: This instance follows value.                        
                    // read the next line that is not empty nor starting with %
                    while ((line = sr.ReadLine()) != null && (line == "" || line[0].CompareTo('%') == 0)) { }
                    EmailAccount = line;

                    while ((line = sr.ReadLine()) != null && (line == "" || line[0].CompareTo('%') == 0)) { }
                    Password = line;

                    while ((line = sr.ReadLine()) != null && (line == "" || line[0].CompareTo('%') == 0)) { }
                    smtpServer = line;

                    // read the next line that is not empty nor starting with %
                    while ((line = sr.ReadLine()) != null && (line == "" || line[0].CompareTo('%') == 0)) { }
                    SenderDisplayName = line;

                    // read the next line that is not empty nor starting with %
                    while ((line = sr.ReadLine()) != null && (line == "" || line[0].CompareTo('%') == 0)) { }
                    smtpPort = line;

                    sr.Close();
                }
            }
            catch (Exception e)
            {
                return 3;
            }

            return 0;
        }
        int read_purchase_confirmation_txt_file()
        {
            //read email details from email_content.txt file
            try
            {
                // Create an instance of StreamReader to read from a file.
                // The using statement also closes the StreamReader.
                using (StreamReader sr = new StreamReader(purchase_confirmation_path))
                {
                    String line;
                    //igure the lines begin with %
                    while ((line = sr.ReadLine()) != null && (line == "" || line[0].CompareTo('%') == 0)) { }
                    purchase_confirmation_subject = line;

                    while ((line = sr.ReadLine()) != null && (line == "" || line[0].CompareTo('%') == 0)) { }
                    purchase_confirmation_body_unpaid = line;

                    while ((line = sr.ReadLine()) != null && (line == "" || line[0].CompareTo('%') == 0)) { }
                    purchase_confirmation_body_paid = line;

                    sr.Close();
                }
            }
            catch (Exception e)
            {
                // Let the user know what went wrong.
                //Console.WriteLine("The file could not be read:");
                //Console.WriteLine(e.Message);
                return 3;
            }
            return 0;
        }
        int read_delivery_confirmation_txt_file()
        {
            //read email details from email_content.txt file
            try
            {
                // Create an instance of StreamReader to read from a file.
                // The using statement also closes the StreamReader.
                using (StreamReader sr = new StreamReader(delivery_confirmation_path))
                {
                    String line;
                    //igure the lines begin with %
                    while ((line = sr.ReadLine()) != null && (line == "" || line[0].CompareTo('%') == 0)) { }
                    delivery_confirmation_subject = line;

                    while ((line = sr.ReadLine()) != null && (line == "" || line[0].CompareTo('%') == 0)) { }
                    delivery_confirmation_body = line;

                    sr.Close();
                }
            }
            catch (Exception e)
            {
                // Let the user know what went wrong.
                //Console.WriteLine("The file could not be read:");
                //Console.WriteLine(e.Message);
                return 3;
            }
            return 0;
        }
        int read_signature_txt_file()
        {
            //read email details from email_content.txt file
            try
            {
                // Create an instance of StreamReader to read from a file.
                // The using statement also closes the StreamReader.
                using (StreamReader sr = new StreamReader(signature_path))
                {
                    String line;
                    //igure the lines begin with %
                    while ((line = sr.ReadLine()) != null && (line == "" || line[0].CompareTo('%') == 0)) { }
                    Signature = line;

                    sr.Close();
                }
            }
            catch (Exception e)
            {
                // Let the user know what went wrong.
                //Console.WriteLine("The file could not be read:");
                //Console.WriteLine(e.Message);
                return 3;
            }
            return 0;
        }
        //void CreatCongFile()
        //{
        //    StreamWriter sw = new StreamWriter(email_account_path, true);
        //}

        #region local variables
        SaleRecord sale;
        Customer customer;
        string EmailAccount;
        string Password;
        string SenderDisplayName = null;
        string smtpServer = "smtp.gmail.com";
        string smtpPort;
        string Signature;               
        string purchase_confirmation_subject;
        string purchase_confirmation_body_unpaid;
        string purchase_confirmation_body_paid;
        string delivery_confirmation_subject;
        string delivery_confirmation_body;
        string email_account_path = "../../Configurations/Email/email_account.txt";
        string purchase_confirmation_path = "../../Configurations/Email/purchase_confirmation.txt";
        string delivery_confirmation_path = "../../Configurations/Email/delivery_confirmation.txt";
        string signature_path = "../../Configurations/Email/signature.txt";
        #endregion
    }
}
