using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Threading.Tasks;
using System.Linq;
using System.Text;
using System.Windows.Input;
using System.Windows.Threading;
using MarketData;
using MarketData.Utils;
using MarketData.MarketDataModel;
using MarketData.Generator;
using MarketData.DataAccess;
using TradeBlotter.DataAccess;
using TradeBlotter.Model;
using TradeBlotter.Command;
using Microsoft.Research.DynamicDataDisplay.DataSources;
using TradeBlotter.Cache;
using MarketData.Generator.MovingAverage;

namespace TradeBlotter.ViewModels
{
  public class MovingAverageViewModel : WorkspaceViewModel
  {
    private MovingAverages movingAverages;
    private String symbol;
    private String companyName;
    private List<String> symbols;
    private List<String> watchLists;
    private String selectedWatchList;
    private RelayCommand refreshCommand;
    private List<Int32> dayCounts;
    private Int32 selectedDayCount;
    private PortfolioTrades portfolioTrades;
    private bool busyIndicator = false;
    private String busyContent = "Generating Moving Average";
    private bool isLegendVisible = true;

    public MovingAverageViewModel()
    {
      base.DisplayName = "MovingAverageView";
      watchLists = WatchListDA.GetWatchLists();
      watchLists.Insert(0, Constants.CONST_ALL);
      selectedWatchList = watchLists.Find(x => x.Equals("Valuations"));
      symbols = WatchListDA.GetWatchList(selectedWatchList);
      dayCounts = new List<Int32>();
      dayCounts.Add(60);
      dayCounts.Add(90);
      dayCounts.Add(180);
      dayCounts.Add(360);
      dayCounts.Add(720);
      dayCounts.Add(1440);
      dayCounts.Add(3600);
      selectedDayCount = dayCounts[3];
      PropertyChanged += OnMovingAverageViewModelPropertyChanged;
    }
    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>("SelectedDayCount", selectedDayCount.ToString()));
      saveParams.Add(new KeyValuePair<String, String>("IsLegendVisible", isLegendVisible.ToString()));
      return saveParams;
    }
    public override void SetSaveParameters(SaveParameters saveParameters)
    {
      try
      {
        symbol = (from KeyValuePair<String, String> item in saveParameters where item.Key.Equals("SelectedSymbol") select item).FirstOrDefault().Value;
        selectedWatchList = (from KeyValuePair<String, String> item in saveParameters where item.Key.Equals("SelectedWatchList") select item).FirstOrDefault().Value;
        base.OnPropertyChanged("SelectedWatchList");
        selectedDayCount = Int32.Parse((from KeyValuePair<String, String> item in saveParameters where item.Key.Equals("SelectedDayCount") select item).FirstOrDefault().Value);
        try{isLegendVisible = Boolean.Parse((from KeyValuePair<String, String> item in saveParameters where item.Key.Equals("IsLegendVisible") select item).FirstOrDefault().Value);}
        catch (Exception){;}
        Referer=saveParameters.Referer;
        base.OnPropertyChanged("SelectedSymbol");
      }
      catch (Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,String.Format("Exception:{0}",exception.ToString()));
      }
    }
    public override bool CanPersist()
    {
      return true;
    }
    private void OnMovingAverageViewModelPropertyChanged(object sender, PropertyChangedEventArgs eventArgs)
    {
      if (eventArgs.PropertyName.Equals("SelectedSymbol")||(eventArgs.PropertyName.Equals("SelectedDayCount")&&null!=symbol))
      {
        BusyIndicator = true;
        Task workerTask = Task.Factory.StartNew(() =>
        {
          companyName = PricingDA.GetNameForSymbol(symbol);
          movingAverages = MovingAverageGenerator.GenerateMovingAverages(symbol, selectedDayCount);
          if (null != movingAverages) portfolioTrades = PortfolioDA.GetOpenTradesSymbolBetween(symbol, movingAverages.FromDate, movingAverages.ThruDate);
          else portfolioTrades = null;
        });
        workerTask.ContinueWith((continuation) =>
        {
          BusyIndicator = false;
          base.OnPropertyChanged("Close");
          base.OnPropertyChanged("High");
          base.OnPropertyChanged("Low");
          base.OnPropertyChanged("MA200");
          base.OnPropertyChanged("MA100");
          base.OnPropertyChanged("MA55");
          base.OnPropertyChanged("MA21");
          base.OnPropertyChanged("MA5");
          base.OnPropertyChanged("Title");
          base.OnPropertyChanged("TradePoints");
          base.OnPropertyChanged("LegendVisible");
        });
      }
      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");
      }
    }
    public bool BusyIndicator
    {
      get { return busyIndicator; }
      set
      {
        busyIndicator = value;
        base.OnPropertyChanged("BusyIndicator");
      }
    }
    public String BusyContent
    {
      get { return busyContent; }
    }
    public CompositeDataSource Close
    {
      get
      {
        CompositeDataSource compositeDataSource = MovingAverageModel.Close(movingAverages);
        return compositeDataSource;
      }
    }
    public CompositeDataSource High
    {
      get
      {
        CompositeDataSource compositeDataSource = MovingAverageModel.High(movingAverages);
        return compositeDataSource;
      }
    }
    public CompositeDataSource Low
    {
      get
      {
        CompositeDataSource compositeDataSource = MovingAverageModel.Low(movingAverages);
        return compositeDataSource;
      }
    }
    public CompositeDataSource MA200
    {
      get
      {
        CompositeDataSource compositeDataSource = MovingAverageModel.MA200(movingAverages);
        return compositeDataSource;
      }
    }
    public CompositeDataSource MA100
    {
      get
      {
        CompositeDataSource compositeDataSource = MovingAverageModel.MA100(movingAverages);
        return compositeDataSource;
      }
    }
    public CompositeDataSource MA55
    {
      get
      {
        CompositeDataSource compositeDataSource = MovingAverageModel.MA55(movingAverages);
        return compositeDataSource;
      }
    }
    public CompositeDataSource MA21
    {
      get
      {
        CompositeDataSource compositeDataSource = MovingAverageModel.MA21(movingAverages);
        return compositeDataSource;
      }
    }
    public CompositeDataSource MA5
    {
      get
      {
        CompositeDataSource compositeDataSource = MovingAverageModel.MA5(movingAverages);
        return compositeDataSource;
      }
    }
    public CompositeDataSource TradePoints
    {
      get
      {
        CompositeDataSource compositeDataSource = PortfolioTradeModel.PortfolioTrades(portfolioTrades);
        return compositeDataSource;
      }
    }
    public override String Title
    {
      get
      {
        if (null == companyName || null == movingAverages || 0 == movingAverages.Count) return "";
        StringBuilder sb=new StringBuilder();
        String displayCompanyName=companyName;
        if(displayCompanyName.Length>40) displayCompanyName=displayCompanyName.Substring(0,40)+"...";
        sb.Append(displayCompanyName);
        sb.Append(" (").Append(symbol).Append(") ").Append(Utility.DateTimeToStringMMHDDHYYYY(movingAverages.FromDate)).Append(" Thru ").Append(Utility.DateTimeToStringMMHDDHYYYY(movingAverages.ThruDate));
        Prices prices=PricingDA.GetPrices(symbol,2);
        if(2==prices.Count)
        {
          float change=prices.GetReturns()[0];
          sb.Append(" (").Append(Utility.FormatCurrency(prices[0].Close));
          sb.Append("/").Append(Utility.FormatCurrency(prices[0].Low));
          if(!float.IsNaN(change))
          {
            sb.Append(",");
            sb.Append(change>=0.00?"+":"").Append(Utility.FormatPercent((double)change));
          }
          sb.Append(")");
        }
        return sb.ToString();
      }
    }
    public Boolean CheckBoxLegendVisible
    {
      get
      {
        return isLegendVisible;
      }
      set
      {
        isLegendVisible = value;
        base.OnPropertyChanged("CheckBoxLegendVisible");
        base.OnPropertyChanged("LegendVisible");
      }
    }
    public String LegendVisible
    {
      get
      {
        if (isLegendVisible) return "true";
        return "false";
      }
      set
      {
        isLegendVisible = Boolean.Parse(value);
        base.OnPropertyChanged("LegendVisible");
      }
    }
    public List<Int32> DayCounts
    {
      get { return dayCounts; }
    }
    public Int32 SelectedDayCount
    {
      get { return selectedDayCount; }
      set { selectedDayCount = value; base.OnPropertyChanged("SelectedDayCount"); }
    }
    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 List<String> WatchListNames
    {
      get
      {
        return watchLists;
      }
      set { ;}
    }
    public String SelectedWatchList
    {
      get { return selectedWatchList; }
      set { selectedWatchList = value; base.OnPropertyChanged("SelectedWatchList"); }
    }
    private void Refresh()
    {
      base.OnPropertyChanged("SelectedSymbol");
    }
    private Boolean CanRefresh
    {
      get { return true; }
    }
    public ICommand RefreshCommand
    {
      get
      {
        if (null == refreshCommand) refreshCommand = new RelayCommand(param => Refresh(), param => CanRefresh);
        return refreshCommand;
      }
    }
  }
}
