using System;
using System.Windows;
using System.Windows.Controls;
using System.ComponentModel;

namespace MyAuth
{
    public partial class LoginControl : UserControl
    {
        AuthenticationModel _model;

        public LoginControl()
        {
            InitializeComponent();

            _btnLogin.Click += _btnLogin_Click;
            _btnLogout.Click += _btnLogout_Click;
            _btnHello.Click += _btnHello_Click;

            if (!DesignerProperties.IsInDesignTool)
            {
                Model = new AuthenticationModel();
            }
        }
        public AuthenticationModel Model
        {
            get { return DataContext as AuthenticationModel; }
            set
            {
                DataContext = value;
                UpdateDataContext();
            }
        }
        void UpdateDataContext()
        {
            if (_model != null)
            {
                _model.PropertyChanged -= _model_PropertyChanged;
            }
            _model = DataContext as AuthenticationModel;
            if (_model != null)
            {
                _model.PropertyChanged += _model_PropertyChanged;
            }
            UpdateUI();
        }
        void _model_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            UpdateUI();
        }
        void UpdateUI()
        {
            if (_model != null)
            {
                _btnHello.Content = "Hello " + _model.User.FriendlyName;
                var loggedin = _model.User.IsAuthenticated;
                _spLogin.Visibility = loggedin ? Visibility.Collapsed : Visibility.Visible;
                _spLogout.Visibility = loggedin ? Visibility.Visible : Visibility.Collapsed;
            }
        }

        // log out
        void _btnLogout_Click(object sender, RoutedEventArgs e)
        {
            if (_model != null)
            {
                _model.Logout(null);
            }
        }

        // log in
        void _btnLogin_Click(object sender, RoutedEventArgs e)
        {
            ModalDialog.Show(this, "Log in", new LoginPanel());
        }
        void _btnHello_Click(object sender, RoutedEventArgs e)
        {
            ModalDialog.Show(this, "Account Information", new AccountInfoPanel());
        }
    }
}
