using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ComponentPro.Net.Mail;

namespace ScanMessages
{
    /// <summary>
    /// Interaction logic for Main.xaml
    /// </summary>
    public partial class Main : Window
    {
        public Main()
        {
            InitializeComponent();
            txtPath.Text = DataDir;
        }

        string _dataDir;
        /// <summary>
        /// Gets the default data folder that stores Messages.
        /// </summary>
        public string DataDir
        {
            get
            {
                _dataDir = System.IO.Path.GetFullPath(AppDomain.CurrentDomain.BaseDirectory + "..\\..\\Data");
                if (!System.IO.Directory.Exists(_dataDir))
                    _dataDir = AppDomain.CurrentDomain.BaseDirectory + "Data";

                return _dataDir;
            }
        }

        private void btnBrowse_Click(object sender, RoutedEventArgs e)
        {
            // Open Folder Browser Dialog.
            System.Windows.Forms.FolderBrowserDialog dlg = new System.Windows.Forms.FolderBrowserDialog();
            dlg.SelectedPath = txtPath.Text;
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtPath.Text = dlg.SelectedPath;
            }
        }

        private void btnScan_Click(object sender, RoutedEventArgs e)
        {
            BounceInspector inspector = new BounceInspector();
            inspector.Progress += inspector_Progress;

            ltvResult.Items.Clear();

            try
            {
                // Scan messages.
                BounceResultCollection result = inspector.ProcessMessages(txtPath.Text);

                string found = string.Format("{0}/{1} bounced e-mails found.", result.BounceCount, result.Count);
                if (result.HasErrors)
                    found += "\r\nCompleted with errors.";

                System.Windows.MessageBox.Show(result.CancelledIndex != -1 ? "Operation has been cancelled by user. " + found : found, "BounceInspector", MessageBoxButton.OK);
            }
            catch (Exception exc)
            {
                ShowError(exc);       
            }
        }

        private void inspector_Progress(object sender, ProgressEventArgs e)
        {
            Dispatcher.Invoke(new EventHandler<ProgressEventArgs>(Filter_Progress), sender, e);
        }

        class CustomListItem
        {
            public string File
            {
                get;set;
            }
            public string Subject
            {
                get;set;
            }
            public string Email
            {
                get;set;
            }
            public string Category
            {
                get;set;
            }
            public string Type
            {
                get;set;
            }
            public string DSNAction
            {
                get;set;
            }
            public string DSNDiagnosticCode
            {
                get;set;
            }
        }

        /// <summary>
        /// Handles the BounceInspector's Progress event.
        /// </summary>
        /// <param name="sender">The BounceInspector object.</param>
        /// <param name="e">The event arguments.</param>
        private void Filter_Progress(object sender, ProgressEventArgs e)
        {
            try
            {
                BounceResult r = e.Result;

                if (r.MailMessage == null)
                    return;

                if (r.Identified)
                {
                    CustomListItem item = new CustomListItem();

                    item.File = System.IO.Path.GetFileName(r.FilePath);
                    item.Subject = r.MailMessage.Subject;
                    item.Email = r.Addresses[0];
                    item.Category = r.BounceCategory.Name;
                    item.Type = r.BounceType.Name;
                    item.DSNAction = r.Dsn.Action.ToString();
                    item.DSNDiagnosticCode = r.Dsn.DiagnosticCode;

                    ltvResult.Items.Add(item);
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }

        public static void ShowError(Exception exc)
        {
            string str;

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

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