using MarketData.DataAccess;
using MarketData.MarketDataModel;
using MarketData.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using TradeBlotter.Cache;

namespace TradeBlotter.UIUtils
{
  /// <summary>
  /// Interaction logic for ProformaAddPosition.xaml
  /// </summary>
  public partial class ProformaAddPositionDialog : Window
  {
    private List<String> symbols;
    private List<String> accounts;
    private ManualResetEvent manualResetEvent = new ManualResetEvent(false);

    private String Account { get; set; }
    private DateTime PurchaseDate { get; set; }
    private double PurchasePrice { get; set; }
    private String SelectedSymbol { get; set; }
    private double Exposure { get; set; }
    private double Shares { get; set; }
    private bool Result { get; set; }

    private ProformaAddPositionDialog(String title,String account, DateTime purchaseDate, PortfolioTrades portfolioTrades)
    {
      this.Background = new SolidColorBrush(Colors.AliceBlue);
      this.Owner = Application.Current.MainWindow;
      InitializeComponent();
      this.Loaded += new RoutedEventHandler(AddPositionDialog_Loaded);
      this.Closing += Window_Closing;
      cbSymbols.SelectionChanged += cbSymbols_SelectionChanged;
      txtPurchasePrice.SelectionChanged += txtPurchasePrice_SelectionChanged;
      txtShares.SelectionChanged += txtShares_SelectionChanged;
      txtExposure.TextChanged += txtExposure_SelectionChanged;
      dpPurchaseDate.SelectedDateChanged += dpPurchaseDate_SelectionChanged;

//      symbols=PricingDA.GetSymbols();     
      symbols=SymbolCache.GetInstance().GetSymbols();
      Title = title;
      Shares = 0.00;
      Exposure = 0.00;
      Account = account;
      accounts=PortfolioDA.GetAccounts();
      if(null==Account||!accounts.Any(x=>x.Equals(account)))Account=accounts[0];
      cbAccounts.ItemsSource = accounts;
      cbAccounts.SelectedItem = Account;
      cbSymbols.ItemsSource = symbols;
      cbSymbols.SelectedItem = symbols[0];
      if (Utility.IsEpoch(purchaseDate)) PurchaseDate = PricingDA.GetLatestDate();
      else PurchaseDate = purchaseDate;
      dpPurchaseDate.SelectedDate = PurchaseDate;
      UpdatePrice();
      txtShares.Text = Utility.FormatNumber(Shares, 3);
    }
    public ManualResetEvent Event { get {return manualResetEvent;}}
    public static PortfolioTrades Prompt(string title,String account,DateTime effectiveDate,PortfolioTrades portfolioTrades)
    {
      ProformaAddPositionDialog proformaAddPositionDialog = new ProformaAddPositionDialog(title,account, effectiveDate, portfolioTrades);
      proformaAddPositionDialog.SelectedSymbol = null;
      try { proformaAddPositionDialog.ShowDialog(); }
      catch (Exception) { return portfolioTrades; }
      proformaAddPositionDialog.Event.WaitOne();
      if (proformaAddPositionDialog.Result == true)
      {
        PortfolioTrade portfolioTrade = proformaAddPositionDialog.CreatePortfolioTrade();
        portfolioTrades.Add(portfolioTrade);
      }
      return portfolioTrades;
    }
    void AddPositionDialog_Loaded(object sender, RoutedEventArgs e)
    {
        cbSymbols.Focus();
    }
    public PortfolioTrade CreatePortfolioTrade()
    {
      try                                                     
      {
        PortfolioTrade portfolioTrade=new PortfolioTrade();
        portfolioTrade.Account = Account;
        portfolioTrade.BuySell = "B";
        portfolioTrade.Status = "OPEN";
        portfolioTrade.Price = PurchasePrice;
        portfolioTrade.Symbol = SelectedSymbol;
        portfolioTrade.Shares = Shares;
        portfolioTrade.TradeDate = PurchaseDate;
        return portfolioTrade;
      }
      catch (Exception)
      {
        return null;
      }
    }
    private void btnOk_Click(object sender, RoutedEventArgs e)
    {
      Result = Validate();
      Close();
      Event.Set();
      return;
    }
    private void cbSymbols_SelectionChanged(object sender, RoutedEventArgs e)
    {
      SelectedSymbol = cbSymbols.SelectedValue.ToString();
      UpdatePrice();
      UpdateExposure();
      UpdateCompanyName();
    }
    private void txtPurchasePrice_SelectionChanged(object sender, RoutedEventArgs e)
    {
      double value=0.00;
      value = Utility.ParseCurrency(txtPurchasePrice.Text);
      if (PurchasePrice.Equals(value)) return;
      PurchasePrice = value;
      if (!txtPurchasePrice.IsFocused)
      {
        UpdatePrice();
        UpdateExposure();
      }
      else UpdateExposure();
    }
    private void txtShares_SelectionChanged(object sender, RoutedEventArgs e)
    {
      double value = 0.00;
      double.TryParse(txtShares.Text, out value);
      if (Shares.Equals(value)) return;
      Shares = Math.Round(value,3);
      if (txtShares.IsFocused)
      {
        UpdatePrice();                                                 
        UpdateExposure();
      }
    }
    private void dpPurchaseDate_SelectionChanged(object sender, RoutedEventArgs e)
    {
      if (null == dpPurchaseDate.SelectedDate) return;
      PurchaseDate = dpPurchaseDate.SelectedDate.Value;
      UpdatePrice();
      UpdateExposure();
    }
    private void txtExposure_SelectionChanged(object sender, RoutedEventArgs e)
    {
      if (null == txtExposure.Text || "".Equals(txtExposure.Text)) return;
      double value=Utility.ParseCurrency(txtExposure.Text);
      if (0.00 == value || value==Exposure) return;
      txtExposure.Text = Utility.FormatCurrency(value);
      txtExposure.CaretIndex = txtExposure.Text.IndexOf('.');
      if (0.00 == PurchasePrice) return;
      Shares = Math.Round(value / PurchasePrice,3);
      if (txtExposure.IsFocused)
      {
        UpdateShares();
      }
    }
    private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
      Event.Set();
    }
    private void btnCancel_Click(object sender, RoutedEventArgs e)
    {
      Result = false;
      Close();
      Event.Set();
    }
    private bool Validate()
    {
      if (null == SelectedSymbol) return false;
      if(null==Account)return false;
      if(Utility.IsEpoch(PurchaseDate))return false;
      if (double.IsNaN(PurchasePrice)) return false;
      if (0 == Shares) return false;
      return true;
    }
    private void UpdatePrice()
    {
      if (Utility.IsEpoch(PurchaseDate)) return;
      Price price = PricingDA.GetPrice(SelectedSymbol, PurchaseDate);
      if (null == price)
      {
        DateGenerator dateGenerator = new DateGenerator();
        DateTime prevBusinessDate=dateGenerator.FindPrevBusinessDay(PurchaseDate);
        price = PricingDA.GetPrice(SelectedSymbol, prevBusinessDate);
        if (null != price) { PurchasePrice = price.Close; PurchaseDate = prevBusinessDate; dpPurchaseDate.SelectedDate = PurchaseDate; }
        else PurchasePrice = 0.00;
      }
      else PurchasePrice = price.Close;
      txtPurchasePrice.Text = Utility.FormatCurrency(PurchasePrice);
    }
    private void UpdateExposure()
    {
      Exposure = PurchasePrice * Shares;
      txtExposure.Text = Utility.FormatCurrency(Exposure);
    }
    private void UpdateShares()
    {
      txtShares.Text = Utility.FormatNumber(Shares,3);
    }
    private void UpdateCompanyName()
    {
      CompanyProfile companyProfile = CompanyProfileDA.GetCompanyProfile(SelectedSymbol);
      if (null == companyProfile||null==companyProfile.CompanyName) return;
      lblCompanyName.Content = companyProfile.CompanyName.ToUpper();
    }
  }
}
                                    