using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Windows.Input;
using MarketData.MarketDataModel;
using MarketData.Service;
using Navigator.Core;
using Navigator.Models;
using Navigator.Views;
using Xamarin.Forms;

namespace Navigator.ViewModels
{
    public class GainLossViewModel : WorkspaceViewModel 
    {
      private ObservableCollection<String> accounts=null;
      private ObservableCollection<GainLossSummaryItemDetail> gainLossSummaryItemDetails=null;
      private RelayCommand refreshCommand;
      private String listViewSelectedItem=null;
			private GainLossSummaryItemDetail gainLossSummaryItemSelectedItem=null;
      private bool isRefreshing=false;
      private bool showActivity = true;

      public GainLossViewModel()
      {
        Title="Gain/Loss";
        DateTime latestPricingDate=DateTime.Now;
        ServiceResult serviceResult=MarketDataServiceClient.GetInstance().GetLatestPricingDate();
        if(serviceResult.Success)latestPricingDate=(DateTime)serviceResult.ContextSpecificResult;
        //Initialize();
        //PropertyChanged+=OnViewModelPropertyChanged;
        PropertyChanged+=OnViewModelPropertyChanged;
        Initialize();
      }
      private void OnViewModelPropertyChanged(object sender,PropertyChangedEventArgs eventArgs)
      {
        if(eventArgs.PropertyName.Equals("ListViewSelectedItem"))
        {
          HandleListViewSelectedItem();
        }
				else if(eventArgs.PropertyName.Equals("GainLossSummaryItemDetailSelectedItem"))
				{
				  HandleGainLossSummaryItemDetailSelectedItem();
				}
      }
      public void HandleListViewSelectedItem()
      {
        IsBusy=true;
        ShowActivity=!IsRefreshing;
        Task workerTask=Task.Factory.StartNew(()=>
        {
          try
          {
            if(!String.IsNullOrEmpty(listViewSelectedItem)) 
            {
              ServiceResult serviceResult=null;
              if("ALL".Equals(listViewSelectedItem))serviceResult=MarketDataServiceClient.GetInstance().GetGainLossDetails(DateTime.Now);
              else serviceResult=MarketDataServiceClient.GetInstance().GetGainLossDetails(DateTime.Now,listViewSelectedItem);

              if(serviceResult.Success)
              {
                List<GainLossSummaryItemDetail> gainLossSummaryItems=(List<GainLossSummaryItemDetail>)serviceResult.ContextSpecificResult;
                if(null!=gainLossSummaryItems)
                {
                  foreach(GainLossSummaryItemDetail gainLossSummaryItem in gainLossSummaryItems)
                  {
                    if(!String.IsNullOrEmpty(gainLossSummaryItem.CompanyName)&&gainLossSummaryItem.CompanyName.Length>30)gainLossSummaryItem.CompanyName=gainLossSummaryItem.CompanyName.Substring(0,30)+"...";
                  }
                  GainLossSummary=new ObservableCollection<GainLossSummaryItemDetail>(gainLossSummaryItems);
                }
              }
              //else
              //{
              //  Debug.WriteLine(serviceResult.Message);
              //}
            }
          }
          finally
          {
          }
        });
        workerTask.ContinueWith((continuation)=>
        {
          IsBusy=false;
          IsRefreshing=false;
          ShowActivity=!IsRefreshing;
        });
      }

			public void HandleGainLossSummaryItemDetailSelectedItem()
			{
        if(null==gainLossSummaryItemSelectedItem || string.IsNullOrEmpty(gainLossSummaryItemSelectedItem.Symbol)) return;
				DataStore.AddItem(new Item("BollingerBandViewModelSymbol", gainLossSummaryItemSelectedItem.Symbol,"Symbol"));
			  Application.Current.MainPage.Navigation.PushModalAsync(new BollingerBandPage());
        GainLossSummaryItemDetailSelectedItem=null;
      }

  public ObservableCollection<GainLossSummaryItemDetail> GainLossSummary
      {
        get{return gainLossSummaryItemDetails;}
        set{SetProperty(ref gainLossSummaryItemDetails,value);}
      }
      public ObservableCollection<String> Accounts
      {
        get{return accounts;}
        set { SetProperty(ref accounts, value); }
      }
      public void Initialize()
      {
        IsBusy=true;
        Task workerTask=Task.Factory.StartNew(()=>
        {
          ServiceResult serviceResult = MarketDataServiceClient.GetInstance().GetAccountsWithOpenTrades();
          if (serviceResult.Success)
          {
            List<String> accounts = (List<String>)serviceResult.ContextSpecificResult;
            accounts.Insert(0, "ALL");
            Accounts = new ObservableCollection<string>(accounts);
//            ListViewSelectedItem="ALL";
          }
        });
        workerTask.ContinueWith((continuation)=>
        {
          IsBusy=false;
          ListViewSelectedItem="ALL";
        });
      }
      public String ListViewSelectedItem
      {
        get
        {
          return listViewSelectedItem;
        }
        set
        {
          SetProperty(ref listViewSelectedItem,value);
        }
      }

			public GainLossSummaryItemDetail GainLossSummaryItemDetailSelectedItem
			{
			  get
				{
				  return gainLossSummaryItemSelectedItem;
				}
				set
				{
				  SetProperty(ref gainLossSummaryItemSelectedItem, value);
				}
			}

		  public bool IsRefreshing
      {
        get{return isRefreshing;}
        set{SetProperty(ref isRefreshing,value);}
      }

      // If the Refreshing Indicstor is showing we don't want to show the ControlTemplate indicator... but we do want the screen to shade while the operation runs
      public bool ShowActivity
      {
        get {return showActivity;}
        set {SetProperty(ref showActivity,value);}
      }

      public ICommand RefreshCommand
      {
        get
        {
          if(null==refreshCommand)
          {
            refreshCommand=new RelayCommand(param=>
            {
              HandleListViewSelectedItem();
//              IsRefreshing=false;
            },param=>{return !IsRefreshing;});
          }
          return refreshCommand;
        }
      }
    }
}
