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;
using ComponentPro;

namespace EmailValidatorDemo
{
    /// <summary>
    /// Interaction logic for Main.xaml
    /// </summary>
    public partial class Main : Window
    {
        public Main()
        {
            InitializeComponent();

            emailValidator.ValidateCompleted += emailValidator_ValidateCompleted;
            emailValidator.MessageLogging += emailValidator_MessageLogging;
            emailValidator.EmailValidated += emailValidator_EmailValidated;   
        }

        void emailValidator_EmailValidated(object sender, EmailValidatedEventArgs e)
        {
            if (e.Error != null)
            {
                lst1AdvancedLog.Items.Add(string.Format("Email '{0}' validated at level {1} with error: {2}.", e.EmailAddress, e.ValidatedLevel, e.Error.Message));
            }
            else
            {
                lst1AdvancedLog.Items.Add(string.Format("Email '{0}' validated at level {1}.", e.EmailAddress, e.ValidatedLevel));                
            }            
        }

        EmailValidator emailValidator = new EmailValidator();

        void EnableSingleMode(bool enable)
        {
            txtEmailSingle.IsEnabled = enable;
            btnValidateSingle.Content = enable ? "Validate" : "Stop";
            if (enable)
                btnValidateSingle.IsEnabled = true;
        }

        private void btnVerify_Click(object sender, RoutedEventArgs e)
        {
            // Is not validating?
            if ((string)btnValidateSingle.Content == "Validate")
            {                
                // Clear logs.
                lst1AdvancedLog.Items.Clear();
                try
                {
                    EnableSingleMode(false);

                    // Asynchronously validate a single email.
                    emailValidator.ValidateAsync(txtEmailSingle.Text);
                }
                catch (Exception exc)
                {
                    MessageBox.Show(exc.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Stop);
                    EnableSingleMode(true);
                }
            }
            else
            {
                // Abort the validation.
                btnValidateSingle.IsEnabled = false;
                emailValidator.Cancel();
            }
        }

        /// <summary>
        /// Handles the emailvalidator's MessageLogging event.
        /// </summary>
        /// <param name="sender">The emailvalidator object.</param>
        /// <param name="e">The event arguments.</param>
        void emailValidator_MessageLogging(object sender, EmailValidatorLogEventArgs e)
        {
            string msg = e.SmtpTranscript.Replace("\r\n", string.Empty);

            lst1AdvancedLog.Items.Add(msg);
        }

        void emailValidator_ValidateCompleted(object sender, ExtendedAsyncCompletedEventArgs<ValidationLevel> e)
        {
            if (e.Error != null)
            {
                ShowError(e.Error);
            }
            else
            {
                // Get the validation result.
                ValidationLevel level = e.Result;

                MessageBox.Show("E-mail address validation completed at level: " + level.ToString(), "Email Validator Demo", MessageBoxButton.OK, MessageBoxImage.Information);
            }            

            EnableSingleMode(true);
        }

        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");
        }
    }
}
