using System;
using System.ComponentModel;
using System.Text;
using System.Windows.Forms;
using ComponentPro;
using ComponentPro.Net;
using ComponentPro.Net.Mail;

namespace ImapDownloader
{
    public partial class Imap : Form
    {
        private readonly bool _exception;
        string _mailsDir;
        string _workingDir;
        bool _disconnect;
        bool _disconnected;

        /// <summary>
        /// Gets the working directory.
        /// </summary>
        public string WorkingDir
        {
            get
            {
                if (_workingDir == null)
                {
                    _workingDir = AppDomain.CurrentDomain.BaseDirectory.EndsWith("\\") ? AppDomain.CurrentDomain.BaseDirectory : (AppDomain.CurrentDomain.BaseDirectory + '\\');
                }

                return _workingDir;
            }
        }

        /// <summary>
        /// Gets the directory which is used to store mails.
        /// </summary>
        public string MailsDir
        {
            get
            {
                if (_mailsDir == null)
                {
                    _mailsDir = WorkingDir;

                    if (!System.IO.Directory.Exists(_mailsDir + "..\\..\\Mails"))
                        _mailsDir += "Mails";
                    else
                        _mailsDir += "..\\..\\Mails";
                }

                return _mailsDir;
            }
        }

        /// <summary>
        /// Constructor.
        /// </summary>
        public Imap()
        {
            try
            {
                InitializeComponent();
            }
            catch (ComponentPro.Licensing.Mail.UltimateLicenseException exc)
            {
                MessageBox.Show(exc.Message, "Error");
                _exception = true;
                return;
            }

            cbxSecurity.SelectedIndex = 0;
            // The following settings are for a gmail Mailbox:
            //cbxSecurity.SelectedIndex = 2;
            //txtServer.Text = "myserver";
            //txtPort.Text = "993";
            //txtUserName.Text = "someone@gmail.com";
            //txtPassword.Text = "password";
            txtFolder.Text = "Inbox";

            imapClient.Timeout = 20000;
            imapClient.Proxy.ProxyType = ProxyType.None;

            // Prepare the Mails folder for storing downloaded messages.
            if (!System.IO.Directory.Exists(MailsDir))
                System.IO.Directory.CreateDirectory(MailsDir);

        }

        /// <summary>
        /// Handles the form's Load event.
        /// </summary>
        /// <param name="e">The event arguments.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (_exception)
                this.Close();
        }

        /// <summary>
        /// Adds a line to the result listbox.
        /// </summary>
        /// <param name="str">Text to write.</param>
        private void WriteLine(string str)
        {
            lsbResult.Items.Add(str);
        }

        /// <summary>
        /// Adds a formatted line to the result listbox.
        /// </summary>
        /// <param name="str">Formatted text to write.</param>
        /// <param name="parameters">The parameters for the formatted text.</param>
        private void WriteLine(string str, params object[] parameters)
        {
            lsbResult.Items.Add(string.Format(str, parameters));
        }

        /// <summary>
        /// Handles the Download button's Click event.
        /// </summary>
        /// <param name="sender">The button object.</param>
        /// <param name="e">The event arguments.</param>
        async void btnDownload_Click(object sender, EventArgs e)
        
        {
            if (btnDownload.Text == "Download")
            {
                int port;

                if (string.IsNullOrEmpty(txtServer.Text))
                {
                    MessageBox.Show("Please enter server name", "Error");
                    return;
                }

                try
                {
                    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 (string.IsNullOrEmpty(txtUserName.Text))
                {
                    MessageBox.Show("Please enter user name");
                    return;
                }

                if (string.IsNullOrEmpty(txtPassword.Text))
                {
                    MessageBox.Show("Please enter password");
                    return;
                }

                if (string.IsNullOrEmpty(txtFolder.Text))
                {
                    MessageBox.Show("Folder name cannot be empty");
                    return;
                }

                _disconnect = false;
                _disconnected = false;

                grbAuth.Enabled = false;
                grbFolder.Enabled = false;
                grbServer.Enabled = false;
                //grbStatus.Enabled = false;

                progressBarTotal.Value = 0;
                progressBar.Value = 0;

                btnDownload.Text = "Cancel";
                // Change image.
                this.btnDownload.Image = ImapDownloader.Properties.Resources.Stop;
                btnProxy.Enabled = false;

                WriteLine("Connecting to the IMAP server {0}:{1}, security: {2}...",
                    txtServer.Text, port, cbxSecurity.Text);

                SecurityMode sec;

                switch (cbxSecurity.SelectedIndex)
                {
                    case 0:
                        sec = SecurityMode.None;
                        break;

                    case 1:
                        sec = SecurityMode.Explicit;
                        break;

                    default:
                        sec = SecurityMode.Implicit;
                        break;
                }

                try
                {
                    // Asynchronously connects to the IMAP server.
                    await imapClient.ConnectAsync(txtServer.Text, port, sec);
                }
                catch (Exception ex)
                {
                    ShowError(ex);
                    Disconnect();
                    return;
                }
                
                Authenticate();
            }
            else
            {
                imapClient.Cancel();
                // Waits for the last pending operation.
                _disconnect = true;
                btnDownload.Enabled = false;
                //btnClose.Enabled = false;
            }
        }

        
        async void Authenticate()
        
        {
            // Disconnects if user clicks on the Close button or the Cancel button.
            if (_disconnect)
            {
                Disconnect();
                return;
            }
            WriteLine("Connected.");
            WriteLine("Authorizing as {0}...", txtUserName.Text);

            try
            {
                await imapClient.AuthenticateAsync(txtUserName.Text, txtPassword.Text);
            }
            catch (Exception ex)
            {
                ShowError(ex);
                Disconnect();
                return;
            }

            SelectFolder();
        }


        async void SelectFolder()
        {
            if (_disconnect)
            {
                Disconnect();
                return;
            }
            WriteLine("Logged In.");
            WriteLine("Selecting working folder {0}...", txtFolder.Text);

            try
            {
                // Asynchronously select a folder to download messages.
                await imapClient.SelectAsync(txtFolder.Text, true);
            }
            catch (Exception ex)
            {
                ShowError(ex);
                Disconnect();
                return;
            }

            ListMessages();
        }


        async void ListMessages()
        {
            if (_disconnect)
            {
                Disconnect();
                return;
            }

            // Get current folder.
            Folder folder = imapClient.WorkingFolder;
            WriteLine("Folder selected and {0} messages found.", folder.TotalMessages);

            WriteLine("Retrieving the list of messages...");
            try
            {
                // Asynchronously get message list.
                _list = await imapClient.ListMessagesAsync(ImapEnvelopeParts.UniqueId);
            }
            catch (Exception ex)
            {
                ShowError(ex);
                Disconnect();
                return;
            }

            WriteLine("List of messages retrieved.");
            _index = 0;
            try
            {
                // Download EML files.
                while (!_disconnect)
                {
                    await DownloadEml();
                }
            }
            catch (Exception ex)
            {
                if (!(ex is OperationCanceledException))
                    ShowError(ex);
            }
            finally
            {
                Disconnect();
            }
        }


        /// <summary>
        /// Shows an error.
        /// </summary>
        /// <param name="exc">Exception object.</param>
        private static void ShowError(Exception exc)
        {
            string str;

            if (exc.InnerException != null)
            {
                str = string.Format(null, "An error occurred: {0}\r\n{1}", exc.Message, exc.InnerException.Message);
            }
            else
                str = string.Format(null, "An error occurred: {0}", exc.Message);

            MessageBox.Show(str, "Error");
        }

        /// <summary>
        /// Disconnects to the IMAP server.
        /// </summary>
        async void Disconnect()
        {
            WriteLine("Disconnecting...");
            try
            {
                await imapClient.DisconnectAsync();
            }
            catch (Exception ex)
            {
                ShowError(ex);
            }
            finally
            {
                SetDisconnectedStatus();
            }
        }

        void SetDisconnectedStatus()
        {
            WriteLine("Disconnected.");

            grbAuth.Enabled = true;
            grbFolder.Enabled = true;
            grbServer.Enabled = true;
            //grbStatus.Enabled = true;

            progressBarTotal.Value = 0;
            progressBar.Value = 0;

            btnDownload.Text = "Download";
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ImapDownloader.Imap));
            this.btnDownload.Image = (System.Drawing.Image)resources.GetObject("btnDownload.Image");
            btnProxy.Enabled = true;
            btnDownload.Enabled = true;

            _disconnected = true;
            _disconnect = false;
        }


        ImapMessageCollection _list;
        int _index;


        /// <summary>
        /// Downloads EML files.
        /// </summary>
        System.Threading.Tasks.Task<long> DownloadEml()
            
        {
            Retry:
            if (_disconnect)
            {
                Disconnect();
                throw new OperationCanceledException();
            }
            if (_index < _list.Count)
            {
                ImapMessage message = _list[_index++];
                string fileName = MailsDir + "\\" + GetFilename(message.UniqueId) + ".eml";

                // Skip if it exists,
                if (System.IO.File.Exists(fileName))
                {
                    WriteLine("Skipping message '{0}'...", message.UniqueId);
                    goto Retry;
                }

                WriteLine("Retrieving message '{0}'...", message.UniqueId);
                progressBarTotal.Value = _index * 100 / _list.Count;
                // Asynchronously get message.
                return imapClient.DownloadMessageAsync(message.UniqueId, fileName);
            }
            else
            {
                Disconnect();
                throw new OperationCanceledException();
            }
        }

        /// <summary>
        /// Returns a uniquely correct file name from the specified unique message ID.
        /// </summary>
        /// <param name="uniqueId">The unique id.</param>
        /// <returns>The corrected file name.</returns>
        private static string GetFilename(string uniqueId)
        {
            // Characters allowed in the filename
            //string allowed = " .-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";            
            const string allowed = " .-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

            // Replace invalid charactes with its hex representation
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < uniqueId.Length; i++)
            {
                if (allowed.IndexOf(uniqueId[i]) < 0)
                    sb.AppendFormat("_{0:X2}", (int)uniqueId[i]);
                else
                    sb.Append(uniqueId[i]);
            }
            return sb.ToString();
        }

        /// <summary>
        /// Handles the proxy settings button's Click event.
        /// </summary>
        /// <param name="sender">The button object.</param>
        /// <param name="e">The event arguments.</param>
        private void btnProxy_Click(object sender, EventArgs e)
        {
            // Creates new ProxySettings dialog and initialize all parameters.
            ProxySettings proxy = new ProxySettings();
            proxy.ProxyServer = imapClient.Proxy.Server;
            proxy.Port = imapClient.Proxy.Port;
            proxy.UserName = imapClient.Proxy.UserName;
            proxy.Password = imapClient.Proxy.Password;
            proxy.Domain = imapClient.Proxy.Domain;
            proxy.AuthenticationMethod = imapClient.Proxy.AuthenticationMethod;
            proxy.Type = imapClient.Proxy.ProxyType;
            // Popups the ProxySetting dialog.
            if (proxy.ShowDialog() == DialogResult.OK)
            {
                // Updates settings.
                imapClient.Proxy.Server = proxy.ProxyServer;
                if (proxy.Port > 0)
                    imapClient.Proxy.Port = proxy.Port;
                imapClient.Proxy.UserName = proxy.UserName;
                imapClient.Proxy.Password = proxy.Password;
                imapClient.Proxy.Domain = proxy.Domain;
                imapClient.Proxy.AuthenticationMethod = proxy.AuthenticationMethod;
                imapClient.Proxy.ProxyType = proxy.Type;
            }
        }

        /// <summary>
        /// Handles the form's Closing event.
        /// </summary>
        /// <param name="e">The event arguments.</param>
        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            // Connected?
            if (btnDownload.Text == "Cancel")
            {
                // Disconnect.
                _disconnect = true;

                // Wait for the completion.
                while (!_disconnected)
                {
                    System.Threading.Thread.Sleep(50);
                    System.Windows.Forms.Application.DoEvents();
                }
            }

            base.OnClosing(e);
        }

        private void imapClient_Progress(object sender, ImapProgressEventArgs e)
        {
            if (e.State == MailClientTransferState.Downloading)
            {
                progressBar.Value = (int) e.Percentage;
                Application.DoEvents();
            }
        }
    }
}
