using System;
using System.ComponentModel;
using System.Windows.Documents;
using System.Windows.Controls;
using System.Windows;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Threading.Tasks;
using System.Threading;
using System.Linq;
using System.Text;
using MarketData;
using MarketData.DataAccess;
using MarketData.MarketDataModel;
using MarketData.Utils;
using TradeBlotter.Model;
using TradeBlotter.Cache;

namespace TradeBlotter.ViewModels
{
  public class SECFilingViewModel : WorkspaceViewModel
  {
    private List<String> watchLists;
    private String selectedWatchList;
    private String symbol;
    private String selectedCompany;
    private List<String> symbols;
    private SECFilings secFilings = null;
    private int selectedFormIndex = -1;
    private bool busyIndicator = false;

    public SECFilingViewModel()
    {
      base.DisplayName = "SECFilingView";
      watchLists = WatchListDA.GetWatchLists();
      watchLists.Insert(0, Constants.CONST_ALL);
      selectedWatchList = watchLists.Find(x => x.Equals("Valuations"));
      symbols = WatchListDA.GetWatchList(selectedWatchList);
      PropertyChanged += OnSECFilingViewModelPropertyChanged;
    }
    public override SaveParameters GetSaveParameters()
    {
      SaveParameters saveParams = new SaveParameters();
      if (null == symbol) return null;
      saveParams.Add(new KeyValuePair<String, String>("Type", GetType().Namespace + "." + GetType().Name));
      saveParams.Add(new KeyValuePair<String, String>("SelectedSymbol", symbol));
      saveParams.Add(new KeyValuePair<String, String>("SelectedWatchList", selectedWatchList));
      saveParams.Add(new KeyValuePair<String, String>("SelectedFormIndex", selectedFormIndex.ToString()));
      return saveParams;
    }
    public override void SetSaveParameters(SaveParameters saveParameters)
    {
      try
      {
        Referer=saveParameters.Referer;
        symbol = (from KeyValuePair<String, String> item in saveParameters where item.Key.Equals("SelectedSymbol") select item).FirstOrDefault().Value;
        base.OnPropertyChanged("SelectedSymbol");
        try{selectedWatchList = (from KeyValuePair<String, String> item in saveParameters where item.Key.Equals("SelectedWatchList") select item).FirstOrDefault().Value;}catch(Exception){;}
        try{selectedFormIndex = Int32.Parse((from KeyValuePair<String, String> item in saveParameters where item.Key.Equals("SelectedFormIndex") select item).FirstOrDefault().Value);}catch(Exception){;}
        base.OnPropertyChanged("SelectedFormIndex");
      }
      catch (Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,String.Format("Exception:{0}",exception.ToString()));
      }
    }
    public override bool CanPersist()
    {
      return true;
    }                                                                   
    public bool BusyIndicator
    {
      get { return busyIndicator; }
      set
      {
        busyIndicator = value;
        base.OnPropertyChanged("BusyIndicator");
      }
    }
    public String BusyContent
    {
      get { return "Loading SEC Filings..."; }
    }
    private void OnSECFilingViewModelPropertyChanged(object sender, PropertyChangedEventArgs eventArgs)
    {
      if (eventArgs.PropertyName.Equals("SelectedSymbol") && null != symbol)
      {
        BusyIndicator = true;
        Task workerTask=Task.Factory.StartNew(() =>
        {
          secFilings = SECFilingDA.GetSECFilings(symbol);
          selectedCompany = PricingDA.GetNameForSymbol(symbol);
        });
        workerTask.ContinueWith((continuation)=>
        {
          BusyIndicator = false;
          base.OnPropertyChanged("FormNames");
          base.OnPropertyChanged("Title");
          selectedFormIndex = 0;
          base.OnPropertyChanged("SelectedFormIndex");
        });
      }
      else if (eventArgs.PropertyName.Equals("SelectedWatchList"))
      {
//        if (selectedWatchList.Equals(Constants.CONST_ALL)) symbols = PricingDA.GetSymbols();
        if (selectedWatchList.Equals(Constants.CONST_ALL)) symbols = SymbolCache.GetInstance().GetSymbols();
        else symbols = WatchListDA.GetWatchList(selectedWatchList);
        base.OnPropertyChanged("Symbols");
      }
      else if (eventArgs.PropertyName.Equals("SelectedFormIndex"))
      {
        base.OnPropertyChanged("Document");
        base.OnPropertyChanged("Title");
      }
    }
    public List<String> WatchListNames
    {
      get
      {
        return watchLists;
      }
//      set { ;}
    }
    public List<String> Symbols
    {
      get
      {
        return symbols;
      }
    }
    public String SelectedSymbol
    {
      get { return symbol; }
      set
      {
        if (value == symbol || String.IsNullOrEmpty(value)) return;
        symbol = value;
        base.OnPropertyChanged("SelectedSymbol");
      }
    }
    public String SelectedWatchList
    {
      get { return selectedWatchList; }
      set { selectedWatchList = value; base.OnPropertyChanged("SelectedWatchList"); }
    }
    public IList<Item> FormNames
    {
      get
      {
        if(null==secFilings)return null;
        List<Item> formNames = new List<Item>();
        foreach (SECFiling secFiling in secFilings) formNames.Add(new Item(secFiling.Description));
        return formNames;
      }
    }
    public int SelectedFormIndex
    {
      get { return selectedFormIndex; }
      set 
      { 
        selectedFormIndex = value;
        base.OnPropertyChanged("SelectedFormIndex");
      }
    }
    public override String Title
    {
      get 
      {
        if (null == symbol || selectedFormIndex < 0 || null==selectedCompany) return "";
        if (null == secFilings || 0 == secFilings.Count || selectedFormIndex < 0) return "";
        return selectedCompany + "("+symbol+") " + " Filed:" + Utility.DateTimeToStringMMSDDSYYYY(secFilings[selectedFormIndex].FilingDate) + ", Accession #:" + secFilings[selectedFormIndex].SECAccessionNumber+" #:"+secFilings[selectedFormIndex].Sequence;
      }
    }
    public String Document
    {
      get
      {
        String emptyText = "<html>No SEC Filings found for "+symbol+"</html>";
        if (null == symbol || selectedFormIndex < 0) return "<html></html>";
        if (null == secFilings||0==secFilings.Count||selectedFormIndex<0) return emptyText;
        return secFilings[selectedFormIndex].FormText;
      }
    }
  }
}