using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Collections;
using System.IO;
using System.Threading;
using System.Xml;
namespace OutlookExpress_V1._._
{
    public partial class frmSendReceive : Form
    {
        ArrayList attachments;
        ArrayList popAttachmentsIndex;
        Pop3Client pop = null;
        private int maxMail = 0;
        private string PSN = "";
        private string SSN = "";
        private string PP = "";
        private string SP = "";
        private string UN = "";
        private string PW = "";
        public frmSendReceive()
        {
            InitializeComponent();
            this.attachments = new ArrayList();
            this.popAttachmentsIndex = new ArrayList();
        }

        private void frmSendReceive_Load(object sender, EventArgs e)
        {

        }

        private void GetMailServerSetting()
        {
            try
            {
                if (File.Exists("PerlLookUpS.xml"))
                {
                    DataSet ds = new DataSet();
                    ds.ReadXml(@"PerlLookUpS.xml");
                    DataTable dt = new DataTable();
                    dt = ds.Tables[0];
                    PSN = dt.Rows[0][0].ToString();
                    PP = dt.Rows[0][1].ToString();
                    SSN = dt.Rows[0][2].ToString();
                    SP = dt.Rows[0][3].ToString();
                    UN = dt.Rows[0][4].ToString();
                    PW = dt.Rows[0][5].ToString();
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void ConnectToServer()
        {
            if (this.CheckInputValidationForPop(PSN, PP, UN, PW))
            {
                if (Internet.IsConnectedToInternet())
                {
                    ReceiveEmails();
                }
                else
                {
                    MessageBox.Show(this, "You must connect to the internet.", "Send / Receive", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }

        private void pop_Disconnected(object sender, string Server)
        {
            if (this.statusStrip.InvokeRequired)
            {
                DisconnectEventHandler discon = new DisconnectEventHandler(this.pop_Disconnected);
                this.Invoke(discon, new object[] { sender, Server });
            }
            else
            {
                lblR.Text = "Disconnected with the pop server \"" + Server + "\"";
                lblRS.Text = "Disconnected";
            }
        }

        private void pop_EndedDataReceiving(object sender)
        {
            if (this.statusStrip.InvokeRequired)
            {
                DataReceivingEventHandler data = new DataReceivingEventHandler(this.pop_EndedDataReceiving);
                this.Invoke(data, new object[] { sender });
            }
            else
            {
                lblRS.Text = "Email message has received";
            }
        }

        private void pop_StartedDataReceiving(object sender)
        {
            if (this.statusStrip.InvokeRequired)
            {
                DataReceivingEventHandler data = new DataReceivingEventHandler(this.pop_StartedDataReceiving);
                this.Invoke(data, new object[] { sender });
            }
            else
            {
                lblRS.Text = "Receiving email message";
            }
        }

        private void pop_AuthenticationFinished(object sender, string userName)
        {
            if (this.statusStrip.InvokeRequired)
            {
                AuthenticateEventHandler auth = new AuthenticateEventHandler(this.pop_AuthenticationFinished);
                this.Invoke(auth, new object[] { sender, userName });
            }
            else
            {
                lblRS.Text = "Verification is completed";
            }
        }

        private void pop_AuthenticationBegan(object sender, string userName)
        {
            if (this.statusStrip.InvokeRequired)
            {
                AuthenticateEventHandler auth = new AuthenticateEventHandler(this.pop_AuthenticationBegan);
                this.Invoke(auth, new object[] { sender, userName });
            }
            else
            {
                lblRS.Text = "Verifying user name and password";
            }
        }

        private void pop_ConnectionEstablished(object sender, string Server, int Port)
        {
            if (this.statusStrip.InvokeRequired)
            {
                ConnectEventHandler con = new ConnectEventHandler(this.pop_ConnectionEstablished);
                this.Invoke(con, new object[] { sender, Server, Port });
            }
            else
            {
                lblRS.Text = "Connection is established with the pop server \"" + Server + "\"";
            }
        }

        private void pop_ConnectionEstablishing(object sender, string Server, int Port)
        {
            if (this.statusStrip.InvokeRequired)
            {
                ConnectEventHandler con = new ConnectEventHandler(this.pop_ConnectionEstablishing);
                this.Invoke(con, new object[] { sender, Server, Port });
            }
            else
            {
                lblRS.Text = "Connecting to pop server \"" + Server + "\" on port " + Port;
            }
        }
        // The delegate used to enable or disable a button control, in another thread
        private delegate void EnableDisableEventHandler(bool enable);

        // The delegate used to insert an item in the Inbox ListView
        private delegate void InboxItemEventHandler(ListViewItem item);

        // The delegate used to Add attached file names in Pop Attachments ListView

        // The delegate used to clear the items in Pop Attachments ListView


        // The delegate used to write Pop Message in browser
        private delegate void WritePopMessageEventHandler(string content);


        // The delegate used to update Status Bar
        private delegate void UpdateStatusBarEventHandler(string text);


        private void ReceiveEmails()
        {
            try
            {

                if (pop.TotalEmails >= 1)
                {
                    lblRS.Text = "Retrieving Emails";
                    FillInboxListView(pop);
                    lblRS.Text = "Send / Receive";
                }
                else
                {
                    lblRS.Text = "Send / Receive";
                    MessageBox.Show(this, "No email message exists in the inbox!.", "Send / Receive", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (SmtpClientException err)
            {
                MessageBox.Show(this, err.ErrorMessage, "Send / Receive", MessageBoxButtons.OK, MessageBoxIcon.Error);
                lblRS.Text = "Send / Receive";
            }
        }

        private void ConnectEmails()
        {
            try
            {
                Pop3Client pop_client = new Pop3Client();
                pop_client.Pop3Server = PSN;
                pop_client.Pop3Port = Convert.ToInt32(PP);
                pop_client.UserName = UN;
                pop_client.Password = PW;

                pop_client.ConnectionEstablishing += new ConnectEventHandler(this.pop_ConnectionEstablishing);
                pop_client.ConnectionEstablished += new ConnectEventHandler(this.pop_ConnectionEstablished);
                pop_client.AuthenticationBegan += new AuthenticateEventHandler(this.pop_AuthenticationBegan);
                pop_client.AuthenticationFinished += new AuthenticateEventHandler(this.pop_AuthenticationFinished);
                pop_client.StartedDataReceiving += new DataReceivingEventHandler(this.pop_StartedDataReceiving);
                pop_client.EndedDataReceiving += new DataReceivingEventHandler(this.pop_EndedDataReceiving);
                pop_client.Disconnected += new DisconnectEventHandler(this.pop_Disconnected);

                this.pop = pop_client;

                pop_client.Connect();
                pop_client.GetMailBoxDetails();   //it sets the TotalEmails and TotalEmailSize properties
            }
            catch (SmtpClientException err)
            {
                MessageBox.Show(this, err.ErrorMessage, "Send / Receive", MessageBoxButtons.OK, MessageBoxIcon.Error);
                lblRS.Text = "Send / Receive";
            }
        }


        private bool CheckInputValidationForPop(string pop_server, string pop_port, string user_name, string password)
        {
            if (pop_server.Equals(""))
            {
                MessageBox.Show(this, "You must provide pop server address.", "Send / Receive", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            else if (pop_port.Equals(""))
            {
                MessageBox.Show(this, "You must provide pop port number.", "Send / Receive", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            else if (user_name.Equals(""))
            {
                MessageBox.Show(this, "You must provide username.", "Send / Receive", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            else if (password.Equals(""))
            {
                MessageBox.Show(this, "You must provide password.", "Send / Receive", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }

            return true;
        }

        private void FillInboxListView(Pop3Client obj)
        {
            ArrayList sender = new ArrayList();
            ArrayList subject = new ArrayList();
            ArrayList date = new ArrayList();
            ArrayList size = new ArrayList();
            DataSet ds = new DataSet();
            PerlProperties p = new PerlProperties();
            p.CreateFirstFile();
            ds.ReadXml(@"PersonalFolder.xml");
            maxMail = 0;
            for (int l = 0; l <= ds.Tables[0].Rows.Count - 1; l++)
            {
                try
                {
                    if (maxMail < Convert.ToInt16(ds.Tables[0].Rows[l][0].ToString()))
                    {
                        maxMail = Convert.ToInt16(ds.Tables[0].Rows[l][0].ToString());
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            for (int i = maxMail + 1; i <= obj.TotalEmails; i++)
            {
                string emailHeader = obj.FetchEmailTop(i, 0);
                ds.Tables[0].Rows.Add(i, obj.To.ToString(), obj.From.ToString(), obj.CC.ToString(), obj.Subject.ToString(), obj.Date.ToString(), obj.GetMailSize(i), "Inbox", "Unread", "Normal");
                ds.WriteXml(@"PersonalFolder.xml");
                lblR.Text = "Receiving " + i + " Out Of " + obj.TotalEmails;
            }
        }




        private bool RecipientsEmailValidation(string recipient)
        {
            string[] splits = recipient.Split(new char[] { ',', ';' });

            for (int i = 0; i < splits.Length; i++)
            {
                if (this.EmailValidation(splits[i]))
                {
                    continue;
                }
                else
                {
                    return false;
                }
            }

            return true;
        }

        private bool EmailValidation(string email)
        {
            Regex regx = new Regex(@"([a-zA-Z_0-9.-]+\@[a-zA-Z_0-9.-]+\.\w+)", RegexOptions.IgnoreCase);
            if (regx.IsMatch(email))
            {
                return true;
            }
            return false;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnReceive_Click(object sender, EventArgs e)
        {
            lblS.Text = "Getting Mail Server Setting.";
            GetMailServerSetting();
            lblS.Text = "Connecting To Email.";
            ConnectEmails();
            lblS.Text = "Send All Unsent Messages.";
            lblR.Text = "Getting Mails Information.";
            ConnectToServer();
            lblR.Text = "All Mails Received.";
            lblRS.Text = "Done";
        }








    }
}