using System;
using System.Windows;
using System.Windows.Controls;
using System.Text.RegularExpressions;

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

            // handle create account button
            _btnCreateAccount.Click += _btnCreateAccount_Click;
            _txtFriendlyName.TextChanged += _txt_TextChanged;
            _txtEmail.TextChanged += _txt_TextChanged;
            _txtPassword.PasswordChanged += _txt_TextChanged;
            _txtPassword2.PasswordChanged += _txt_TextChanged;
        }

        // create a new account, log in
        void _btnCreateAccount_Click(object sender, RoutedEventArgs e)
        {
            ModalDialog.StartOperation(this);
            try
            {
                var model = DataContext as AuthenticationModel;
                var name = _txtFriendlyName.Text.Trim();
                var pw = _txtPassword.Password.Trim();
                var eMail = _txtEmail.Text.Trim();
                model.CreateUser(eMail, pw, name, true, true, completedNewUser);
            }
            catch (Exception x)
            {
                completedNewUser(x);
            }
        }
        void completedNewUser(Exception x)
        {
            ModalDialog.EndOperation(this, x);
        }

        // enable/disable button
        void _txt_TextChanged(object sender, EventArgs e)
        {
            var name = _txtFriendlyName.Text.Trim();
            var pw = _txtPassword.Password.Trim();
            var pw2 = _txtPassword2.Password.Trim();
            var eMail = _txtEmail.Text.Trim();
            var eMailPattern = @"[\w]+@[^\.]+\.[^\.]+";

            _btnCreateAccount.IsEnabled =
                name.Length > 0 &&
                pw == pw2 &&
                pw.Length >= 4 &&
                Regex.IsMatch(eMail, eMailPattern);
        }
    }
}
