using System;
using System.Windows;
using System.Windows.Controls;
using System.Text;
using System.Text.RegularExpressions;
using System.ServiceModel.DomainServices.Client.ApplicationServices;

namespace MyAuth
{
    public partial class LoginPanel : UserControl
    {
        public LoginPanel()
        {
            InitializeComponent();

            // handle login button
            _btnLogin.Click += _btnLogin_Click;
            _txtEMail.TextChanged += _txt_TextChanged;
            _txtPassword.PasswordChanged += _txt_TextChanged;

            // handle forgot password button
            _btnForgotPassword.Click += _btnForgotPassword_Click;

            // handle create account button
            _btnNewAccount.Click += _btnNewAccount_Click;
        }

        // reset password
        void _btnForgotPassword_Click(object sender, RoutedEventArgs e)
        {
            ModalDialog.Close(this);
            ModalDialog.Show(this, "Reset Password", new ResetPasswordPanel(_txtEMail.Text));
        }

        // create a new account
        void _btnNewAccount_Click(object sender, RoutedEventArgs e)
        {
            ModalDialog.Close(this);
            ModalDialog.Show(this, "Create Account", new NewAccountPanel());
        }

        // log in
        void _btnLogin_Click(object sender, RoutedEventArgs e)
        {
            ModalDialog.StartOperation(this);
            try
            {
                var model = DataContext as AuthenticationModel;
                var eMail = _txtEMail.Text.Trim();
                var pw = _txtPassword.Password.Trim();
                var parms = new LoginParameters(eMail, pw, _chkRememberMe.IsChecked.Value, null);
                model.Login(parms, completedLogIn);
            }
            catch (Exception x)
            {
                completedLogIn(x);
            }
        }
        void completedLogIn(Exception x)
        {
            ModalDialog.EndOperation(this, x);
        }

        // enable/disable login button
        void _txt_TextChanged(object sender, EventArgs e)
        {
            var model = DataContext as AuthenticationModel;
            var pw = _txtPassword.Password.Trim();
            var eMailPattern = @"[\w]+@[^\.]+\.[^\.]+";
            var eMail = _txtEMail.Text.Trim();

            _btnLogin.IsEnabled = 
                model != null &&
                pw.Length >= 4 &&
                Regex.IsMatch(eMail, eMailPattern);

            _btnForgotPassword.IsEnabled =
                Regex.IsMatch(eMail, eMailPattern);
        }
    }
}
