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

namespace TradeBlotter.ViewModels
{
  public class HeadlinesViewModel : WorkspaceViewModel
  {
    private enum Tasks{SelectedSymbol,SelectedDate};
    private Dictionary<Tasks,Semaphore> semaphorePool=new Dictionary<Tasks,Semaphore>();
    private const String DISPLAY_NAME = "Headlines";
    private List<String> symbols;
    private List<String> watchLists;
    private List<String> dates;
    private String selectedWatchList;
    private String selectedSymbol;
    private String selectedCompany;
    private String selectedDate = null;
    private ObservableCollection<HeadlineSentiment> headlinesSentimentCollection = null;
    private bool busyIndicator = false;
    private RelayCommand browserCommand;
    private RelayCommand refreshCommand;
    private RelayCommand stochasticsCommand;
    private RelayCommand relativeStrengthCommand;
    private RelayCommand macdCommand;
    private RelayCommand bollingerBandCommand;
    private RelayCommand priceHistoryCommand;
    private RelayCommand stickerValuationCommand;
    private RelayCommand dcfValuationCommand;
    private RelayCommand dividendHistoryCommand;
    private RelayCommand analystRatingsCommand;
    private RelayCommand displaySECFilingsCommand;
    private RelayCommand movingAverageCommand;
    private RelayCommand displayHistoricalCommand;
    private RelayCommand displayHeadlinesCommand;
    private RelayCommand removeFromWatchListCommand;
    private RelayCommand addToWatchListCommand;
    private RelayCommand proformaDividendRiskCommand = null;
    private HeadlineSentiment selectedItem;

    public HeadlinesViewModel(bool loadedFromParams=false)
    {                                                                    
      semaphorePool.Add(Tasks.SelectedSymbol,new Semaphore(1,1));
      semaphorePool.Add(Tasks.SelectedDate,new Semaphore(1,1));
      base.DisplayName = DISPLAY_NAME;
      watchLists = WatchListDA.GetWatchLists();
      watchLists.Insert(0, Constants.CONST_ALL);
      selectedWatchList = watchLists.Find(x => x.Equals("Valuations"));
      symbols = WatchListDA.GetWatchList(selectedWatchList);
      symbols.Insert(0, Constants.CONST_ALL);
      selectedSymbol=symbols[0];
      dates = HeadlinesDA.GetHeadlineDates();
      if(dates.Count>0)selectedDate = dates[0];
      PropertyChanged += OnHeadlinesViewModelPropertyChanged;
      if(!loadedFromParams)base.OnPropertyChanged("SelectedSymbol");
    }
// ******************************************************************************************** P E R S I S T E N C E ********************************************************************************************
    public override bool CanPersist()
    {
      return true;
    }
    public override SaveParameters GetSaveParameters()
    {
      SaveParameters saveParams = new SaveParameters();
      if (null == selectedSymbol) return null;
      saveParams.Add(new KeyValuePair<String, String>("Type", GetType().Namespace + "." + GetType().Name));
      saveParams.Add(new KeyValuePair<String, String>("SelectedSymbol", selectedSymbol));
      saveParams.Add(new KeyValuePair<String, String>("SelectedCompany", selectedCompany));
      saveParams.Add(new KeyValuePair<String, String>("SelectedWatchList", selectedWatchList));
      saveParams.Add(new KeyValuePair<String, String>("SelectedDate", selectedDate));
      return saveParams;
    }
    public override void SetSaveParameters(SaveParameters saveParameters)
    {
      try
      {
        selectedSymbol = (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;
        selectedCompany = (from KeyValuePair<String, String> item in saveParameters where item.Key.Equals("SelectedCompany") select item).FirstOrDefault().Value;
        selectedDate = (from KeyValuePair<String, String> item in saveParameters where item.Key.Equals("SelectedDate") select item).FirstOrDefault().Value;
        if(null==selectedCompany)selectedCompany=PricingDA.GetNameForSymbol(selectedSymbol);
        if (null == selectedDate || selectedDate!=DateTime.Now.Date.ToShortDateString()) selectedDate = HeadlinesDA.GetMaxHeadlineDate().ToShortDateString();
        Referer=saveParameters.Referer;
        base.OnPropertyChanged("SelectedWatchList");
        base.OnPropertyChanged("SelectedSymbol");
      }
      catch (Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,String.Format("Exception:{0}", exception.ToString()));
      }
    }
// ******************************************************************************************************************************************************
    public bool BusyIndicator
    {
      get { return busyIndicator; }
      set
      {
        busyIndicator = value;
        base.OnPropertyChanged("BusyIndicator");
      }
    }
    public ObservableCollection<MenuItem> MenuItems
    {
      get
      {
        ObservableCollection<MenuItem> collection = new ObservableCollection<MenuItem>();
        collection.Add(new MenuItem() { Text = "Search for articles", MenuItemClickedCommand = DisplayBrowserSearch, StaysOpenOnClick = false });
        collection.Add(new MenuItem() { Text = "Display Bollinger Band", MenuItemClickedCommand = DisplayBollingerBand, StaysOpenOnClick = false });
        collection.Add(new MenuItem() { Text = "Display Sticker Valuation", MenuItemClickedCommand = DisplayStickerValuation, StaysOpenOnClick = false });
        collection.Add(new MenuItem() { Text = "Display Dividend History", MenuItemClickedCommand = DisplayDividendHistory, StaysOpenOnClick = false });
        collection.Add(new MenuItem() { Text = "Display Proforma Dividend Risk", MenuItemClickedCommand = DisplayProformaDividendRisk, StaysOpenOnClick = false });
  			collection.Add(new MenuItem() { Text = "Display Historical", MenuItemClickedCommand = DisplayHistorical, StaysOpenOnClick = false });
        collection.Add(new MenuItem() { Text = "Display Analyst Ratings", MenuItemClickedCommand = DisplayAnalystRatings, StaysOpenOnClick = false });
        collection.Add(new MenuItem() { Text = "Display Stochastics", MenuItemClickedCommand = DisplayStochastics, StaysOpenOnClick = false });
        collection.Add(new MenuItem() { Text = "Display Relative Strength", MenuItemClickedCommand=DisplayRelativeStrength, StaysOpenOnClick = false });
        collection.Add(new MenuItem() { Text = "Display MACD", MenuItemClickedCommand = DisplayMACD, StaysOpenOnClick = false });
        collection.Add(new MenuItem() { Text = "Display Moving Average", MenuItemClickedCommand = DisplayMovingAverage, StaysOpenOnClick = false });
        collection.Add(new MenuItem() { Text = "Display Price History", MenuItemClickedCommand = DisplayPriceHistory, StaysOpenOnClick = false });
        collection.Add(new MenuItem() { Text = "Display DCF Valuation", MenuItemClickedCommand = DisplayDCFValuation, StaysOpenOnClick = false });
  			collection.Add(new MenuItem() { Text = "Display SEC Filings", MenuItemClickedCommand = DisplaySECFilings, StaysOpenOnClick = false });
        collection.Add(new MenuItem() { Text = "Display Headlines", MenuItemClickedCommand = DisplayHeadlines, StaysOpenOnClick = false });
        collection.Add(new MenuItem() { Text = "Remove from Watchlist", MenuItemClickedCommand = RemoveFromWatchList, StaysOpenOnClick = false });
				collection.Add(new MenuItem() { Text = "Add to Watchlist", MenuItemClickedCommand = AddToWatchList, StaysOpenOnClick = false });
        return collection;
      }
    }
    private void OnHeadlinesViewModelPropertyChanged(object sender, PropertyChangedEventArgs eventArgs)
    {
      if (eventArgs.PropertyName.Equals("SelectedDate") )
      {
        HandleSelectedDate();
      }
      else if (eventArgs.PropertyName.Equals("SelectedSymbol")) 
      {
        HandleSelectedSymbol();
      }
      else if (eventArgs.PropertyName.Equals("SelectedWatchList"))
      {
        HandleSelectedWatchList();
      }
    }
    private void HandleSelectedDate()
    {
      try
      {
        semaphorePool[Tasks.SelectedDate].WaitOne();
        BusyIndicator = true;
        Task workerTask = Task.Factory.StartNew(() =>
        {
          if (Constants.CONST_ALL.Equals(selectedDate))
          {
            Headlines headlines=HeadlinesDA.GetHeadlines(selectedSymbol);
            HeadlinesSentiment headlinesSentiment=SentimentGenerator.GetInstance().ProcessHeadlines(headlines);
            selectedCompany = PricingDA.GetNameForSymbol(selectedSymbol);
            if (null != headlinesSentiment && 0 != headlinesSentiment.Count) headlinesSentimentCollection = new ObservableCollection<HeadlineSentiment>(headlinesSentiment);
            else headlinesSentimentCollection = null;
          }
          else if (null != selectedSymbol && !Constants.CONST_ALL.Equals(selectedSymbol))
          {
            Headlines headlines = HeadlinesDA.GetHeadlines(selectedSymbol, DateTime.Parse(selectedDate));
            HeadlinesSentiment headlinesSentiment=SentimentGenerator.GetInstance().ProcessHeadlines(headlines);
            selectedCompany = PricingDA.GetNameForSymbol(selectedSymbol);
            if (null != headlinesSentiment && 0 != headlinesSentiment.Count) headlinesSentimentCollection = new ObservableCollection<HeadlineSentiment>(headlinesSentiment);
            else headlinesSentimentCollection = null;
          }
          else
          {
            Headlines headlines = HeadlinesDA.GetHeadlines(DateTime.Parse(selectedDate));
            HeadlinesSentiment headlinesSentiment=SentimentGenerator.GetInstance().ProcessHeadlines(headlines);
            if (null != headlinesSentiment && 0 != headlinesSentiment.Count) headlinesSentimentCollection = new ObservableCollection<HeadlineSentiment>(headlinesSentiment);
            else headlinesSentimentCollection = null;
          }
        });
        workerTask.ContinueWith((continuation)=>
        {
          BusyIndicator = false;
          base.OnPropertyChanged("AllItems");
          base.OnPropertyChanged("Title");
        });
      }
      finally
      {
        semaphorePool[Tasks.SelectedDate].Release();
      }
    }
    private void HandleSelectedSymbol()
    {
      try
      {
        semaphorePool[Tasks.SelectedSymbol].WaitOne();
        BusyIndicator = true;
        Task workerTask = Task.Factory.StartNew(() =>
        {
//          SentimentGenerator sentimentGenerator=new SentimentGenerator();
          if (null != selectedSymbol && !Constants.CONST_ALL.Equals(selectedSymbol))
          {
            base.DisplayName = DISPLAY_NAME + "(" + selectedSymbol + ")";
            Headlines headlines = HeadlinesDA.GetHeadlines(selectedSymbol);
            HeadlinesSentiment headlinesSentiment=SentimentGenerator.GetInstance().ProcessHeadlines(headlines);
            selectedCompany = PricingDA.GetNameForSymbol(selectedSymbol);
            if (null != headlinesSentiment && 0 != headlinesSentiment.Count) headlinesSentimentCollection = new ObservableCollection<HeadlineSentiment>(headlinesSentiment);
            else headlinesSentimentCollection = null;
//            if (null != headlines && 0 != headlines.Count) headlinesCollection = new ObservableCollection<Headline>(headlines);
//           else headlinesCollection = null;
          }
          else if (null == selectedSymbol || Constants.CONST_ALL.Equals(selectedSymbol))
          {
            Headlines headlines = null;
            if (null == selectedDate || Constants.CONST_ALL.Equals(selectedDate)) headlines = HeadlinesDA.GetHeadlines();
            else headlines = HeadlinesDA.GetHeadlines(DateTime.Parse(selectedDate));
            HeadlinesSentiment headlinesSentiment=SentimentGenerator.GetInstance().ProcessHeadlines(headlines);
            if (null != headlinesSentiment && 0 != headlinesSentiment.Count) headlinesSentimentCollection = new ObservableCollection<HeadlineSentiment>(headlinesSentiment);
            else headlinesSentimentCollection = null;
            //if (null != headlines && 0 != headlines.Count) headlinesCollection = new ObservableCollection<Headline>(headlines);
            //else headlinesCollection = null;
          }
        });
        workerTask.ContinueWith((continuation) =>
        {
          BusyIndicator = false;
          base.OnPropertyChanged("AllItems");
          base.OnPropertyChanged("Title");
          base.OnPropertyChanged("DisplayName");
        });
      }
      finally
      {
        semaphorePool[Tasks.SelectedSymbol].Release();
      }
    }
    private void HandleSelectedWatchList()
    {
//      if (selectedWatchList.Equals(Constants.CONST_ALL)) symbols = PricingDA.GetSymbols();
      if (selectedWatchList.Equals(Constants.CONST_ALL)) symbols = SymbolCache.GetInstance().GetSymbols();
      else
      {
        symbols = WatchListDA.GetWatchList(selectedWatchList);
        symbols.Insert(0, Constants.CONST_ALL);
      }
      base.OnPropertyChanged("Symbols");
    }
    //public ObservableCollection<Headline> AllItems
    //{
    //  get { return headlinesCollection; }
    //}
    public ObservableCollection<HeadlineSentiment> AllItems
    {
      get { return headlinesSentimentCollection; }
    }
// ************************************************************************ T O O L T I P  C A L L O U T S  ****************************************************************
    public String Description
    {
      get
      {
        if(null== selectedItem || null==selectedItem.Symbol)return "No row selected.";
        CompanyProfile companyProfile=CompanyProfileDA.GetCompanyProfile(selectedItem.Symbol);
        if(null==companyProfile || null==companyProfile.Description)return "No description found.";
        return companyProfile.Description;
      }
    }    
    public String Parity
    {
      get
      {
        if(null== selectedItem || null==selectedItem.Symbol)return "No row selected.";
        StringBuilder sb=new StringBuilder();
        PortfolioTrades portfolioTrades=PortfolioDA.GetOpenTradesSymbol(selectedItem.Symbol);
        DateTime currentDate=PricingDA.GetLatestDate(selectedItem.Symbol);
        if(null!=portfolioTrades&&0!=portfolioTrades.Count)
        {
          sb.Append("You own this security (").Append(selectedItem.Symbol).Append(") in ").Append(portfolioTrades.Count).Append(" lot(s).  ").Append("Exposure:").Append(Utility.FormatCurrency(portfolioTrades.Sum(x=>x.Exposure())));
          ParityElement parityElement=ParityGenerator.GenerateBreakEven(selectedItem.Symbol);
          if(null!=parityElement)
          {
            sb.Append("\n").Append(parityElement.ToString());
          }
        }
        else sb.Append("You don't hold any shares of '").Append(selectedItem.Symbol).Append("'");
        sb.Append(".");
        DateGenerator dateGenerator=new DateGenerator();
        DateTime priorDate=dateGenerator.FindPrevBusinessDay(currentDate);
        Price p1=PricingDA.GetPrice(selectedItem.Symbol,currentDate);
        Price p2=PricingDA.GetPrice(selectedItem.Symbol,priorDate);
        if(null==p2&&null!=p1)
        {
          priorDate=dateGenerator.FindPrevBusinessDay(priorDate);
          p2=PricingDA.GetPrice(selectedItem.Symbol,priorDate);
        }
        if(null==p1||null==p2)return sb.ToString();
        sb.Append("\n");
        double change=(p1.Close-p2.Close)/p2.Close;
        sb.Append(String.Format("Latest Price {0} {1} ({2}{3})",Utility.DateTimeToStringMMSDDSYYYY(p1.Date),Utility.FormatCurrency(p1.Close),change<0?"-":"+",Utility.FormatPercent(Math.Abs(change))));
        return sb.ToString();

      }
    }
    public override String DisplayName
    {
      get
      {
        if (null != selectedSymbol && !Constants.CONST_ALL.Equals(selectedSymbol))return "Headline (" + selectedSymbol + ")";
        else return "Headlines";      
      }
    }
    public override String Title
    {
      get 
      {
        StringBuilder sb=new StringBuilder();
        sb.Append("");
        if(null!=headlinesSentimentCollection&&0!=headlinesSentimentCollection.Count) sb.Append(headlinesSentimentCollection.Count).Append(" ");
        if (null != selectedSymbol && !Constants.CONST_ALL.Equals(selectedSymbol))sb.Append("Headline (").Append(selectedSymbol).Append(")");
        else sb.Append("Headlines");
        if(null!=selectedDate)
        {
          DateTime selectedDateDt=DateTime.Parse(selectedDate);
          sb.Append(" on ").Append(selectedDateDt.DayOfWeek).Append(", ").Append(Utility.DateTimeToStringMMMM(selectedDateDt)).Append(" ").Append(selectedDateDt.Day).Append(", ").Append(selectedDateDt.Year);
        }
        if(null!=headlinesSentimentCollection)
        {
          double negativeCount=(from HeadlineSentiment s in headlinesSentimentCollection where s.Sentiment.Equals(LexicalElement.NEGATIVE_SENTIMENT) select s).ToList().Count();
          double positiveCount=(from HeadlineSentiment s in headlinesSentimentCollection where s.Sentiment.Equals(LexicalElement.POSITIVE_SENTIMENT) select s).ToList().Count();
          sb.Append(" (Sentiment : ").Append(Utility.FormatPercent(positiveCount/(positiveCount+negativeCount))).Append(")");
        }
        return sb.ToString();
      }
    }
    private void Refresh()
    {
      symbols = WatchListDA.GetWatchList(selectedWatchList);
      symbols.Insert(0, Constants.CONST_ALL);
      selectedSymbol=symbols[0];
      dates = HeadlinesDA.GetHeadlineDates();
      dates.Insert(0, Constants.CONST_ALL);
      if (dates.Count > 1) selectedDate = dates[1];
      else selectedDate = dates[0];
      base.OnPropertyChanged("Symbols");
      base.OnPropertyChanged("Dates");
      base.OnPropertyChanged("SelectedDate");
      base.OnPropertyChanged("SelectedSymbol");
      base.OnPropertyChanged("Title");
    }
    private bool CanReset
    {
      get { return true; }
    }
    public ICommand RefreshCommand
    {
      get
      {
        if (refreshCommand == null)
        {
          refreshCommand = new RelayCommand(param => this.Refresh(), param => {return true;});
        }
        return refreshCommand;
      }
    }
    public List<String> Dates
    {
      get
      {
        return dates;
      }
    }
    public List<String> Symbols
    {
      get
      {
        return symbols;
      }
    }
    public String SelectedSymbol
    {
      get
      { 
        return selectedSymbol; 
      }
      set
      {
        if (value == selectedSymbol || String.IsNullOrEmpty(value)) return;
        selectedSymbol = value;
        base.OnPropertyChanged("SelectedSymbol");
      }
    }
    public String SelectedDate
    {
      get { return selectedDate; }
      set
      {
        selectedDate = value;
        base.OnPropertyChanged("SelectedDate");
      }
    }
    public List<String> WatchListNames
    {
      get
      {
        return watchLists;
      }
      set { ;}
    }
    public String SelectedWatchList
    {
      get { return selectedWatchList; }
      set { selectedWatchList = value; base.OnPropertyChanged("SelectedWatchList"); }
    }
// **************************************************************************************************************************************************************
// ********************************************************************* I C O M M A N D ************************************************************************
// **************************************************************************************************************************************************************
    public ICommand DisplayHistorical
    {
      get
      {
        if (displayHistoricalCommand == null)
        {
          displayHistoricalCommand = new RelayCommand(param => 
          {
            SaveParameters saveParams = SaveParameters.Parse("Type,TradeBlotter.ViewModels.HistoricalViewModel,SelectedSymbol," + selectedItem.Symbol + ",SelectedWatchList,{All}");
            saveParams.Referer=this;
            WorkspaceInstantiator.Invoke(saveParams);
          }, param => { return null != selectedItem && null != selectedItem.Symbol; });
        }
        return displayHistoricalCommand;
      }
    }
    public ICommand DisplayBrowserSearch
    {
      get
      {
        if (browserCommand == null)
        {
          browserCommand = new RelayCommand(param => this.BrowserSearch(), param => { return null != selectedItem && null != selectedItem.Symbol;;});
        }
        return browserCommand;
      }
    }
    public ICommand DisplaySECFilings
    {
      get
      {
        if (null == displaySECFilingsCommand)
        {
          displaySECFilingsCommand = new RelayCommand(param =>
          {
            SaveParameters saveParams = SaveParameters.Parse("Type,TradeBlotter.ViewModels.SECFilingViewModel,SelectedSymbol," + selectedItem.Symbol + ",SelectedWatchList,Valuations");
            saveParams.Referer=this;
            WorkspaceInstantiator.Invoke(saveParams);
          }, param => { return null != selectedItem && null!=selectedItem.Symbol; });
        }
        return displaySECFilingsCommand;
      }
    }
    public ICommand DisplayAnalystRatings
    {
      get
      {
        if (analystRatingsCommand == null)
        {
          analystRatingsCommand = new RelayCommand(param => this.DisplayAnalystRatingsCommand(), param => { return null != selectedItem && null != selectedItem.Symbol; });
        }
        return analystRatingsCommand;
      }
    }
    public ICommand DisplayMACD
    {
      get
      {
        if (macdCommand == null)
        {
          macdCommand = new RelayCommand(param => this.DisplayMACDCommand(), param => { return null != selectedItem && null != selectedItem.Symbol; });
        }
        return macdCommand;
      }
    }
    public ICommand DisplayMovingAverage
    {
      get
      {
        if (movingAverageCommand == null)
        {
          movingAverageCommand = new RelayCommand(param => this.DisplayMovingAverageCommand(), param => { return null != selectedItem && null != selectedItem.Symbol; });
        }
        return movingAverageCommand;
      }
    }
    public ICommand DisplayStochastics
    {
      get
      {
        if (stochasticsCommand == null)
        {
          stochasticsCommand = new RelayCommand(param => this.DisplayStochasticsCommand(), param => { return null != selectedItem && null != selectedItem.Symbol; });
        }
        return stochasticsCommand;
      }
    }
    public ICommand DisplayRelativeStrength
    {
      get
      {
        if (relativeStrengthCommand == null)
        {
          relativeStrengthCommand = new RelayCommand(param => this.DisplayRelativeStrengthCommand(), 
            param => { return null != selectedItem && null!=selectedItem.Symbol; });
        }
        return relativeStrengthCommand;
      }
    }
    public ICommand DisplayHeadlines
    {
      get
      {
        if (null == displayHeadlinesCommand)
        {
          displayHeadlinesCommand = new RelayCommand(param =>
          {
            SaveParameters saveParams = SaveParameters.Parse("Type,TradeBlotter.ViewModels.HeadlinesViewModel,SelectedSymbol," + selectedItem.Symbol + ",SelectedWatchList,Valuations");
            saveParams.Referer=this;
            WorkspaceInstantiator.Invoke(saveParams);
          }, param => { return null != selectedItem && null!=selectedItem.Symbol; });
        }
        return displayHeadlinesCommand;
      }
    }
    public ICommand RemoveFromWatchList
    {
      get
      {
        if (removeFromWatchListCommand == null)
        {
          removeFromWatchListCommand = new RelayCommand(param => this.RemoveFromWatchListCommand(selectedItem.Symbol),
            param =>
            {
              if (null == selectedItem || null == selectedItem.Symbol) return false;
              if (!WatchListDA.IsInWatchList(selectedItem.Symbol)) return false;
              PortfolioTrades portfolioTrades=PortfolioDA.GetOpenTradesSymbol(selectedItem.Symbol);
              if(null!=portfolioTrades&&0!=portfolioTrades.Count)return false;
              return true;
            });
        }
        return removeFromWatchListCommand;
      }
    }
      public ICommand AddToWatchList
      {
        get
        {
          if (addToWatchListCommand == null)
          {
            addToWatchListCommand = new RelayCommand(param => this.AddToWatchListCommand(selectedItem.Symbol), 
              param => 
              {
                if(null==selectedItem || null==selectedItem.Symbol)return false;
                if (WatchListDA.IsInWatchList(selectedItem.Symbol)) return false;
                return true;
              });
          }
          return addToWatchListCommand;
        }
      }
// *********************************************************************************************************************************************************************
    public void RemoveFromWatchListCommand(String symbol)
    {
      if (!WatchListDA.IsInWatchList(symbol))
      {
        System.Windows.MessageBox.Show("'" + symbol + "' is not in watchlist", "Info", MessageBoxButton.OK, MessageBoxImage.Information);
        return;
      }
      if (!WatchListDA.RemoveFromWatchList(symbol))
      {
        System.Windows.MessageBox.Show("Error removing '" + selectedItem.Symbol + "' from watchlist", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
      }
      else
      {
        System.Windows.MessageBox.Show("Removed '" + selectedItem.Symbol + "'", "Success", MessageBoxButton.OK, MessageBoxImage.Information);
      }
    }
    public void AddToWatchListCommand(String symbol)
    {
      if (WatchListDA.IsInWatchList(symbol))
      {
        System.Windows.MessageBox.Show("'"+symbol+"' is already in watchlist","Info", MessageBoxButton.OK,  MessageBoxImage.Information);
        return;
      }
      if (!WatchListDA.AddToWatchList(symbol))
      {
        System.Windows.MessageBox.Show("Error adding '"+symbol+"' to watchlist","Warning", MessageBoxButton.OK,  MessageBoxImage.Warning);
      }
      else
      {
        System.Windows.MessageBox.Show("Added '"+symbol+"'","Success", MessageBoxButton.OK,  MessageBoxImage.Information);
      }
    }
    public void DisplayAnalystRatingsCommand()
    {
      SaveParameters saveParams = SaveParameters.Parse("Type,TradeBlotter.ViewModels.AnalystRatingsViewModel,SelectedSymbol," + selectedItem.Symbol + ",SelectedWatchList,{All}");
      saveParams.Referer=this;
      WorkspaceInstantiator.Invoke(saveParams);
    }
    public void BrowserSearch()
    {
      Utility.LaunchBrowserSearch(selectedItem.Entry);
    }
    public void DisplayStochasticsCommand()
    {
      SaveParameters saveParams = SaveParameters.Parse("Type,TradeBlotter.ViewModels.StochasticsViewModel,SelectedSymbol," + selectedItem.Symbol + ",SelectedWatchList,{All},SelectedDayCount,180");
      saveParams.Referer=this;
      WorkspaceInstantiator.Invoke(saveParams);
    }
    public void DisplayRelativeStrengthCommand()
    {
      SaveParameters saveParams = SaveParameters.Parse("Type,TradeBlotter.ViewModels.RSIViewModel,SelectedSymbol," + selectedItem.Symbol + ",SelectedWatchList,{All},SelectedDayCount,60,SelectedRSIDayCount,14");
      saveParams.Referer=this;
      WorkspaceInstantiator.Invoke(saveParams);
    }
    public void DisplayMACDCommand()
    {
      SaveParameters saveParams = SaveParameters.Parse("Type,TradeBlotter.ViewModels.MACDViewModel,SelectedSymbol," + selectedItem.Symbol + ",SelectedWatchList,{All},SelectedDayCount,180");
      saveParams.Referer=this;
      WorkspaceInstantiator.Invoke(saveParams);
    }
    public void DisplayMovingAverageCommand()
    {
      SaveParameters saveParams = SaveParameters.Parse("Type,TradeBlotter.ViewModels.MovingAverageViewModel,SelectedSymbol," + selectedItem.Symbol + ",SelectedWatchList,{All},SelectedDayCount,360");
      saveParams.Referer=this;
      WorkspaceInstantiator.Invoke(saveParams);
    }
    public ICommand DisplayStickerValuation
    {
      get
      {
        if (null == stickerValuationCommand)
        {
          stickerValuationCommand = new RelayCommand(param =>
          {
            SaveParameters saveParams = SaveParameters.Parse("Type,TradeBlotter.ViewModels.StickerPriceViewModel,SelectedSymbol," + selectedItem.Symbol + ",SelectedWatchList,{All}");
            saveParams.Referer=this;
            WorkspaceInstantiator.Invoke(saveParams);
          }, param => { return null != selectedItem && null!=selectedItem.Symbol; });
        }
        return stickerValuationCommand;
      }
    }
    public ICommand DisplayDCFValuation
    {
      get
      {
        if (null == dcfValuationCommand)
        {
          dcfValuationCommand = new RelayCommand(param =>
          {
            SaveParameters saveParams = SaveParameters.Parse("Type,TradeBlotter.ViewModels.DCFValuationViewModel,SelectedSymbol," + selectedItem.Symbol + ",SelectedWatchList,{All}");
            saveParams.Referer=this;
            WorkspaceInstantiator.Invoke(saveParams);
          }, param => { return null != selectedItem && null!=selectedItem.Symbol; });
        }
        return dcfValuationCommand;
      }
    }
    public ICommand DisplayPriceHistory
    {
      get
      {
        if (priceHistoryCommand == null)
        {
          priceHistoryCommand = new RelayCommand(param => this.DisplayPriceHistoryCommand(), param => { return null != selectedItem && null != selectedItem.Symbol; });
        }
        return priceHistoryCommand;
      }
    }
    public ICommand DisplayDividendHistory
    {
      get
      {
        if (dividendHistoryCommand == null)
        {
          dividendHistoryCommand = new RelayCommand(param => 
          {
            SaveParameters saveParams = SaveParameters.Parse("Type,TradeBlotter.ViewModels.DividendHistoryViewModel,SelectedSymbol," + selectedItem.Symbol + ",SelectedWatchList,{All}");
            saveParams.Referer=this;
            WorkspaceInstantiator.Invoke(saveParams);
          }, param => { return null != selectedItem && null != selectedItem.Symbol; });
        }
        return dividendHistoryCommand;
      }
    }
    public ICommand DisplayProformaDividendRisk
    {
      get
      {
        if (proformaDividendRiskCommand == null)
        {
          proformaDividendRiskCommand = new RelayCommand(param =>
          {
            SaveParameters saveParams = SaveParameters.Parse("Type,TradeBlotter.ViewModels.DividendRiskParityViewModel,SelectedSymbol," + selectedItem.Symbol + "");
            saveParams.Referer = this;
            WorkspaceInstantiator.Invoke(saveParams);
          }, param => 
          {
            if(null==selectedItem || null==selectedItem.Symbol)return false;
            PortfolioTrades portfolioTrades = PortfolioDA.GetOpenTradesSymbol(selectedItem.Symbol);
            return null!=portfolioTrades && 0!=portfolioTrades.Count; 
           });
        }
        return proformaDividendRiskCommand;
      }
    }
    public void DisplayPriceHistoryCommand()
    {
      SaveParameters saveParams = SaveParameters.Parse("Type,TradeBlotter.ViewModels.PricingViewModel,SelectedSymbol," + selectedItem.Symbol + ",SelectedWatchList,{All},SelectedDayCount,180");
      saveParams.Referer=this;
      WorkspaceInstantiator.Invoke(saveParams);
    }
    public ICommand DisplayBollingerBand
    {
      get
      {
        if (bollingerBandCommand == null)
        {
          bollingerBandCommand = new RelayCommand(param => this.DisplayBollingerBandCommand(), param => { return null != selectedItem && null != selectedItem.Symbol; });
        }
        return bollingerBandCommand;
      }
    }
    public void DisplayBollingerBandCommand()
    {
      SaveParameters saveParams = SaveParameters.Parse("Type,TradeBlotter.ViewModels.BollingerBandViewModel,SelectedSymbol," + selectedItem.Symbol + ",SelectedWatchList,{All},SelectedDayCount,180");
      saveParams.Referer=this;
      WorkspaceInstantiator.Invoke(saveParams);
    }
    public HeadlineSentiment SelectedItem
    {
      get
      {
        return selectedItem;
      }
      set
      {
        selectedItem = value;
      }
    }
    //public Headline SelectedItem
    //{
    //  get
    //  {
    //    return selectedItem;
    //  }
    //  set
    //  {
    //    selectedItem = value;
    //  }
//    }
  }
}
