using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Diagnostics;

namespace InvExplorer
{
    public partial class MainPage : UserControl
    {
        ViewModel _model;

        public MainPage()
        {
            InitializeComponent();

            // listen to changes in the current porfolio
            _model = Application.Current.Resources["_model"] as ViewModel;
            _model.PropertyChanged += _model_PropertyChanged;

            // wire up authentication
            WebContext.Current.Authentication.LoggedIn += Authentication_LoggedIn;
            WebContext.Current.Authentication.LoggedOut += Authentication_LoggedOut;
            
            // disable Silverlight context menu
            LayoutRoot.MouseRightButtonDown += (s, e) => { e.Handled = true; };
        }

        // save portfolio when it changes
        void _model_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "PortfolioDefinition")
            {
                var user = WebContext.Current.User;
                if (_model != null && user.IsAuthenticated)
                {
                    var svc = WebContext.Current.Authentication;
                    if (!svc.IsSavingUser && user.UserData != _model.PortfolioDefinition)
                    {
                        user.UserData = _model.PortfolioDefinition;
                        svc.SaveUser(false);
                        Debug.WriteLine("saved user data" + DateTime.Now.ToLongTimeString());
                    }
                }
            }
        }

        // load user data when user logs in
        void Authentication_LoggedIn(object sender, System.ServiceModel.DomainServices.Client.ApplicationServices.AuthenticationEventArgs e)
        {
            var user = WebContext.Current.User;
            if (_model != null && user.IsAuthenticated)
            {
                try
                {
                    _model.PortfolioDefinition = user.UserData;
                    Debug.WriteLine("loaded user data");
                }
                catch
                {
                    Debug.WriteLine("failed to load from: " + user.UserData);
                }
            }
        }

        // clear portfolio when user logs out
        void Authentication_LoggedOut(object sender, System.ServiceModel.DomainServices.Client.ApplicationServices.AuthenticationEventArgs e)
        {
            if (_model != null)
            {
                _model.Initialize();
            }
        }
    }
}
