using System;
using System.Diagnostics;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Windows.Threading;
using System.Threading.Tasks;
using System.Threading;
using System.Windows;
using System.Linq;
using System.Text;
using System.Windows.Data;
using MarketData.MarketDataModel;
using MarketData.DataAccess;
using MarketData.Utils;
using MarketData;
using TradeBlotter.Command;
using TradeBlotter.ViewModels;
using TradeBlotter.Model;
using TradeBlotter.DataAccess;
using TradeBlotter.Cache;
using TradeBlotter.UIUtils;
using System.Windows.Media;
using Forms=System.Windows.Forms;
using MarketData.Numerical;
using System.Windows.Controls;
using MarketData.Generator;
using MarketData.Generator.Momentum;
using MarketData.Cache;

namespace TradeBlotter.ViewModels
{
  public class MainWindowViewModel : WorkspaceViewModel
  {
    private ReadOnlyCollection<CommandViewModel> commands;
    private ObservableCollection<WorkspaceViewModel> workspaces;
    private ObservableCollection<WorkspaceViewModel> anchorables;
    private ObservableCollection<System.Windows.Controls.MenuItem> menuCollection = new ObservableCollection<System.Windows.Controls.MenuItem>();
    private Dictionary<WorkspaceViewModel,System.Windows.Controls.MenuItem> menuCollectionDictionary=new Dictionary<WorkspaceViewModel,System.Windows.Controls.MenuItem>();
    private SplashScreen splashScreen = new SplashScreen(System.Reflection.Assembly.GetExecutingAssembly(),"Resources/highseas2.jpg");
                                                                      
    public MainWindowViewModel()
    {
      anchorables=new ObservableCollection<WorkspaceViewModel>();
      String principal = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
      StringBuilder sb = new StringBuilder();
      sb.Append("eNavigator").Append(" ").Append("(").Append(principal).Append(")");
      sb.Append("[").Append(Utility.Is64Bit()?"64Bit":"32Bit").Append("]");
      base.DisplayName = sb.ToString();
      Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => { DisplaySplashScreen(); }), DispatcherPriority.Normal);
      DispatcherOperation viewStateOperation=Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => { LoadViewStateThreadProc(); }), DispatcherPriority.Normal);
      viewStateOperation.Completed += (s, e) => 
      { 
        Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => { UpdateMenuItems();  }), DispatcherPriority.Normal);
        if(null==workspaces||0==workspaces.Count)Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => { EarningsDateThreadProc(); }), DispatcherPriority.Normal);
      };
      Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => { HeadlinesThreadProc(); }), DispatcherPriority.Normal);
    }

    private void DisplaySplashScreen()
    {
      if(System.Diagnostics.Debugger.IsAttached)return;
      splashScreen.Show(false);
      splashScreen.Close(new TimeSpan(0,0,3));
    }
    private void HeadlinesThreadProc()
    {
      HeadlinesViewModel workspace = this.Workspaces.FirstOrDefault(vm => vm is HeadlinesViewModel) as HeadlinesViewModel;
      if(null==workspace)return;
      this.SetActiveWorkspace(workspace);
    }
    private void EarningsDateThreadProc()
    {
      ObservableCollection<EarningsAnnouncementModel> earningsAnnouncements=EarningsAnnouncementViewModel.GetEarningsAnnouncements(30);
      if(null!=earningsAnnouncements&&earningsAnnouncements.Count>0)ViewEarningsAnnouncements();
    }
    private void LoadViewStateThreadProc()
    {
      WorkspacePersistenceHelper.Load(WorkspacePersistenceHelper.PARAMS_FILE, this.Workspaces, InstantiateWorkspace);
    }
    private void UpdateMenuItems()
    {
      foreach(WorkspaceViewModel workspace in this.Workspaces)AddMenuItem(workspace);
      base.OnPropertyChanged("MenuItems");
    }
    protected override void OnDispose()
    {
      WorkspacePersistenceHelper.Save(WorkspacePersistenceHelper.PARAMS_FILE, this.Workspaces);
      foreach (WorkspaceViewModel workspaceViewModel in this.Workspaces)
      {
        workspaceViewModel.Dispose();
      }
      try{LocalPriceCache.GetInstance().Dispose();}catch(Exception){;}
      try{GBPriceCache.GetInstance().Dispose();}catch(Exception){;}
      try{PriceCache.GetInstance().Dispose();}catch(Exception){;}
      try{SymbolCache.GetInstance().Dispose();}catch(Exception){;}
      base.OnDispose();
    }
    public override SaveParameters GetSaveParameters()
    {
      return null;
    }
    public override void SetSaveParameters(SaveParameters saveParameters)
    {
    }
    public override bool CanPersist()
    {
      return false;
    }
// ****************************************************************************************************************************************************************
// ************************************************************************** M E N U   M A N A G E M E N T *******************************************************
// ****************************************************************************************************************************************************************
    public ObservableCollection<System.Windows.Controls.MenuItem> MenuItems
    {
      get
      {
        return menuCollection;
      }
    }
    public void AddMenuItem(WorkspaceViewModel viewModel)
    {
      try
      {
        System.Windows.Controls.MenuItem menuItem=new System.Windows.Controls.MenuItem() 
        { 
          Name = "MainWindowViewModelMenu",
          Header = viewModel.Title,Command = new RelayCommand(param=>
          {
            this.SetActiveWorkspace(viewModel);
            return;
          }
          ),
          HorizontalAlignment=HorizontalAlignment.Left,
          VerticalAlignment=VerticalAlignment.Center,
          VerticalContentAlignment=VerticalAlignment.Center,
          HorizontalContentAlignment=HorizontalAlignment.Left
          };
        menuItem.FontWeight=FontWeights.DemiBold;
        menuItem.FontStyle=FontStyles.Italic;

        System.Windows.Data.Binding headerBinding=new System.Windows.Data.Binding("Title");
        headerBinding.Mode=BindingMode.OneWay;
        headerBinding.Source=viewModel;

        System.Windows.Data.Binding displayNameBinding=new System.Windows.Data.Binding("DisplayName");
        displayNameBinding.Mode=BindingMode.OneWay;
        displayNameBinding.Source=viewModel;

        MultiBinding multiBinding=new MultiBinding();
        multiBinding.Mode=BindingMode.OneWay;
        multiBinding.Bindings.Add(displayNameBinding);
        multiBinding.Bindings.Add(headerBinding);
        multiBinding.Converter=new NameMultiValueConverter();
        BindingOperations.SetBinding(menuItem,System.Windows.Controls.MenuItem.HeaderProperty,multiBinding);

        menuCollection.Add(menuItem);
        if(!menuCollectionDictionary.ContainsKey(viewModel))
        {
          menuCollectionDictionary.Add(viewModel,menuItem);
        }
        UIServices.SortMenuItems(menuCollection);
      }
      catch(Exception exception)
      {
        Console.WriteLine(exception.ToString());
      }
      finally
      {
      }
    }
    public void RemoveMenuItem(WorkspaceViewModel viewModel)
    {
      if(!menuCollectionDictionary.ContainsKey(viewModel))return;
      menuCollection.Remove(menuCollectionDictionary[viewModel]);
      menuCollectionDictionary.Remove(viewModel);
    }
// ****************************************************************************************************************************************************************
// ****************************************************************************************************************************************************************
// ****************************************************************************************************************************************************************
    public void InstantiateWorkspace(SaveParameters saveParameters)
    {
      WorkspaceViewModel workspaceViewModel=WorkspacePersistenceHelper.Load(saveParameters, workspaces, InstantiateWorkspace);
      AddMenuItem(workspaceViewModel);
    }
    public ReadOnlyCollection<CommandViewModel> Commands
    {
      get
      {
        if (null == commands)
        {
          List<CommandViewModel> commandList = this.CreateCommands();
          commands = new ReadOnlyCollection<CommandViewModel>(commandList);
        }
        return commands;
      }
    }
    private List<CommandViewModel> CreateCommands()
    {
      return new List<CommandViewModel>
      {
        new CommandViewModel("Gain/Loss",new RelayCommand(ParamArrayAttribute=>this.ViewGainLoss())),
        new CommandViewModel("Headlines",new RelayCommand(ParamArrayAttribute=>this.ViewHeadlines())),
        new CommandViewModel("Bollinger Bands",new RelayCommand(ParamArrayAttribute=>this.ViewBollingerBands())),
        new CommandViewModel("Trade Blotter",new RelayCommand(param=>this.ShowAllTrades())),
        new CommandViewModel("Trade Entry",new RelayCommand(ParamArrayAttribute=>this.EnterNewTrade())),
        new CommandViewModel("Risk - HVaR",new RelayCommand(ParamArrayAttribute=>this.ViewValueAtRisk())),
        new CommandViewModel("Risk Profile",new RelayCommand(ParamArrayAttribute=>this.ViewRiskProfile())),
        new CommandViewModel("Asset Allocation",new RelayCommand(ParamArrayAttribute=>this.ViewAssetAllocation())),
        new CommandViewModel("Dividend History",new RelayCommand(ParamArrayAttribute=>this.ViewDividendHistory())),
        new CommandViewModel("Dividend Payments",new RelayCommand(ParamArrayAttribute=>this.ViewDividendPayments())),
        new CommandViewModel("Dividend Risk Parity",new RelayCommand(ParamArrayAttribute=>this.ViewDividendRiskParity())),
        new CommandViewModel("Treasury Yield Curve",new RelayCommand(ParamArrayAttribute=>this.ViewYieldCurve())),
        new CommandViewModel("Resistance/Support",new RelayCommand(ParamArrayAttribute=>this.ViewResistanceAndSupport())),
        new CommandViewModel("Stochastics",new RelayCommand(ParamArrayAttribute=>this.ViewStochastics())),
        new CommandViewModel("Relative Strength",new RelayCommand(ParamArrayAttribute=>this.ViewRSI())),
        new CommandViewModel("Moving Average",new RelayCommand(ParamArrayAttribute=>this.ViewMovingAverage())),
        new CommandViewModel("MACD",new RelayCommand(ParamArrayAttribute=>this.ViewMACD())),
        new CommandViewModel("Historical",new RelayCommand(ParamArrayAttribute=>this.ViewHistorical())),
        new CommandViewModel("Pricing",new RelayCommand(ParamArrayAttribute=>this.ViewPricing())),
        new CommandViewModel("SEC Filings",new RelayCommand(ParamArrayAttribute=>this.ViewSECFilings())),
        new CommandViewModel("Sticker Price",new RelayCommand(ParamArrayAttribute=>this.ViewStickerPrice())),
        new CommandViewModel("DCF Valuation",new RelayCommand(ParamArrayAttribute=>this.ViewDCFValuation())),
        new CommandViewModel("Valuations",new RelayCommand(ParamArrayAttribute=>this.ViewValuations())),
        new CommandViewModel("Earnings Announcements",new RelayCommand(ParamArrayAttribute=>this.ViewEarningsAnnouncements())),
        new CommandViewModel("Analyst Ratings",new RelayCommand(ParamArrayAttribute=>this.ViewAnalystRatings())),
        new CommandViewModel("ETFHoldings",new RelayCommand(ParamArrayAttribute=>this.ViewETFHoldings())),
        new CommandViewModel("Trade Models",new RelayCommand(ParamArrayAttribute=>this.ViewTradeModels())),
        new CommandViewModel("Momentum Model",new RelayCommand(ParamArrayAttribute=>this.ViewMomentumGenerator())),
        new CommandViewModel("MGSHMomentum Model",new RelayCommand(ParamArrayAttribute=>this.ViewMGSHMomentumGenerator())),
        new CommandViewModel("CMMomentum Model",new RelayCommand(ParamArrayAttribute=>this.ViewCMMomentumGenerator())),
        new CommandViewModel("CMTTrend Model",new RelayCommand(ParamArrayAttribute=>this.ViewCMTTrendGenerator())),
        new CommandViewModel("Options",new RelayCommand(ParamArrayAttribute=>this.ViewOptions())),
        new CommandViewModel("Watch Lists",new RelayCommand(ParamArrayAttribute=>this.ViewWatchLists())),
        new CommandViewModel("Feed Statistics",new RelayCommand(ParamArrayAttribute=>this.ViewFeedStatistics()))
      };
    }
    public ObservableCollection<WorkspaceViewModel> Workspaces
    {
      get
      {
        if (null == workspaces)
        {
          workspaces = new ObservableCollection<WorkspaceViewModel>();
          workspaces.CollectionChanged += this.OnWorkspacesChanged;
        }
        return workspaces;
      }
    }
    public ObservableCollection<WorkspaceViewModel> Anchorables
    {
      get
      {
        return anchorables;
      }
    }
    private void OnWorkspacesChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
      if (e.NewItems != null && e.NewItems.Count != 0)
      {
        foreach (WorkspaceViewModel workspace in e.NewItems)
        {
          workspace.RequestClose += this.OnWorkspaceRequestClose;
        }
      }

      if (e.OldItems != null && e.OldItems.Count != 0)
      {
        foreach (WorkspaceViewModel workspace in e.OldItems)
        {
          workspace.RequestClose -= this.OnWorkspaceRequestClose;
        }
      }
    }
    private void OnWorkspaceRequestClose(object sender, EventArgs e)
    {
      WorkspaceViewModel workspace = sender as WorkspaceViewModel;
      if(1==workspaces.Count)return;       // don't remove the last workspace - issue with RadTabControl and no workspaces
      workspace.Dispose();
      this.Workspaces.Remove(workspace);
      RemoveMenuItem(workspace);
      if(null!=workspace.Referer)this.SetActiveWorkspace(workspace.Referer);
    }

    // *********************************************************************************************************************************************************
    private void ShowAllTrades()
    {
      BlotterViewModel workspace = this.Workspaces.FirstOrDefault(vm => vm is BlotterViewModel) as BlotterViewModel;
      if (null == workspace)
      {
        workspace = new BlotterViewModel(TradeRepository.GetInstance(),new EditHandler(ModifyTrade),new DeleteHandler(DeleteTrade));
        AddMenuItem(workspace);
        this.Workspaces.Add(workspace);
      }
      this.SetActiveWorkspace(workspace);
    }
    private void EnterNewTrade()
    {
      TradeEntryViewModel workspace = null;
      BlotterTradeModel trade = BlotterTradeModel.CreateTrade();
      workspace = new TradeEntryViewModel(trade,TradeRepository.GetInstance());
      this.Workspaces.Add(workspace);
      this.SetActiveWorkspace(workspace);
    }
// *****************************************************************************************************************************
    private void ModifyTrade(int tradeId)
    {
      TradeEntryViewModel workspace = this.Workspaces.FirstOrDefault(vm => vm is TradeEntryViewModel) as TradeEntryViewModel;
      if (null == workspace)
      {
        BlotterTradeModel trade = TradeRepository.GetInstance().GetTrade(tradeId);
        if(null==trade)return;
        trade=trade.Clone();
        workspace=new TradeEntryViewModel(trade,TradeRepository.GetInstance());
        this.Workspaces.Add(workspace);
      }
      else workspace.SetActiveTrade(TradeRepository.GetInstance().GetTrade(tradeId));
      this.SetActiveWorkspace(workspace);
    }
    private void DeleteTrade(int tradeId)
    {
      TradeEntryViewModel workspace = this.Workspaces.FirstOrDefault(vm => vm is TradeEntryViewModel) as TradeEntryViewModel;
      if (null == workspace) return;
      if (workspace.TradeId != tradeId.ToString()) return;
      workspaces.Remove(workspace);
    }
// *****************************************************************************************************************************
    private void ViewFeedStatistics()
    {
      FeedStatisticsViewModel workspace = this.Workspaces.FirstOrDefault(vm => vm is FeedStatisticsViewModel) as FeedStatisticsViewModel;
      if (null == workspace)
      {
        workspace = new FeedStatisticsViewModel();
        workspace.WorkspaceInstantiator = InstantiateWorkspace;
        AddMenuItem(workspace);
        this.Workspaces.Add(workspace);
      }
      this.SetActiveWorkspace(workspace);
    }

    private void ViewMomentumGenerator()
    {
      MomentumViewModel workspace = new MomentumViewModel();
      workspace.WorkspaceInstantiator = InstantiateWorkspace;
      AddMenuItem(workspace);
      this.Workspaces.Add(workspace);
      this.SetActiveWorkspace(workspace);
    }

    private void ViewMGSHMomentumGenerator()
    {
      MGSHMomentumViewModel workspace = new MGSHMomentumViewModel();
      workspace.WorkspaceInstantiator = InstantiateWorkspace;
      AddMenuItem(workspace);
      this.Workspaces.Add(workspace);
      this.SetActiveWorkspace(workspace);
    }

    private void ViewCMMomentumGenerator()
    {
      CMMomentumViewModel workspace = new CMMomentumViewModel();
      workspace.WorkspaceInstantiator = InstantiateWorkspace;
      AddMenuItem(workspace);
      this.Workspaces.Add(workspace);
      this.SetActiveWorkspace(workspace);
    }
    private void ViewCMTTrendGenerator()
    {
      CMTTrendViewModel workspace=new CMTTrendViewModel();
      workspace.WorkspaceInstantiator=InstantiateWorkspace;
      AddMenuItem(workspace);
      this.Workspaces.Add(workspace);
      this.SetActiveWorkspace(workspace);
    }
    private void ViewWatchLists()                                     
    {
      WatchListViewModel workspace = this.Workspaces.FirstOrDefault(vm => vm is WatchListViewModel) as WatchListViewModel;
      if (null == workspace)
      {
        workspace = new WatchListViewModel();
        workspace.WorkspaceInstantiator = InstantiateWorkspace;
        AddMenuItem(workspace);
        this.Workspaces.Add(workspace);
      }
      this.SetActiveWorkspace(workspace);
    }
    private void ViewDividendHistory()
    {
      DividendHistoryViewModel workspace = this.Workspaces.FirstOrDefault(vm => vm is DividendHistoryViewModel) as DividendHistoryViewModel;
      if (null == workspace)
      {
        workspace = new DividendHistoryViewModel();
        AddMenuItem(workspace);
        this.Workspaces.Add(workspace);
      }
      this.SetActiveWorkspace(workspace);
    }
    private void ViewDividendPayments()
    {
      DividendPaymentViewModel workspace = this.Workspaces.FirstOrDefault(vm => vm is DividendPaymentViewModel) as DividendPaymentViewModel;
      if (null == workspace)
      {
        workspace = new DividendPaymentViewModel();
        AddMenuItem(workspace);
        this.Workspaces.Add(workspace);
      }
      this.SetActiveWorkspace(workspace);
    }
    private void ViewDividendRiskParity()
    {
      DividendRiskParityViewModel workspace = null;
      workspace = new DividendRiskParityViewModel();
      AddMenuItem(workspace);
      this.Workspaces.Add(workspace);
      this.SetActiveWorkspace(workspace);
    }
    private void ViewValueAtRisk()
    {
      ValueAtRiskViewModel workspace = this.Workspaces.FirstOrDefault(vm => vm is ValueAtRiskViewModel) as ValueAtRiskViewModel;
      if (null == workspace)
      {
        workspace = new ValueAtRiskViewModel();
        AddMenuItem(workspace);
        this.Workspaces.Add(workspace);
      }
      this.SetActiveWorkspace(workspace);
    }
    private void ViewOptions()
    {
      OptionsViewModel workspace = this.Workspaces.FirstOrDefault(vm => vm is OptionsViewModel) as OptionsViewModel;
      if (null == workspace)
      {
        workspace = new OptionsViewModel();
        workspace.WorkspaceInstantiator = InstantiateWorkspace;
        AddMenuItem(workspace);
        this.Workspaces.Add(workspace);
      }
      this.SetActiveWorkspace(workspace);
    }
    private void ViewEarningsAnnouncements()
    {
      EarningsAnnouncementViewModel workspace = this.Workspaces.FirstOrDefault(vm => vm is EarningsAnnouncementViewModel) as EarningsAnnouncementViewModel;
      if (null == workspace)
      {
        workspace = new EarningsAnnouncementViewModel();
        workspace.WorkspaceInstantiator = InstantiateWorkspace;
        AddMenuItem(workspace);
        this.Workspaces.Add(workspace);
      }
      this.SetActiveWorkspace(workspace);
    }
    private void ViewAnalystRatings()
    {
      AnalystRatingsViewModel workspace = new AnalystRatingsViewModel();
      workspace.WorkspaceInstantiator = InstantiateWorkspace;
      AddMenuItem(workspace);
      this.Workspaces.Add(workspace);
      this.SetActiveWorkspace(workspace);
    }
    private void ViewAssetAllocation()
    {
      SectorViewModel workspace = this.Workspaces.FirstOrDefault(vm => vm is SectorViewModel) as SectorViewModel;
      if (null == workspace)
      {
        workspace = new SectorViewModel();
        AddMenuItem(workspace);
        this.Workspaces.Add(workspace);
      }
      this.SetActiveWorkspace(workspace);
    }
    private void ViewRiskProfile()
    {
      RiskProfileViewModel workspace = this.Workspaces.FirstOrDefault(vm => vm is RiskProfileViewModel) as RiskProfileViewModel;
      if (null == workspace)
      {
        workspace = new RiskProfileViewModel();
        AddMenuItem(workspace);
        this.Workspaces.Add(workspace);
      }
      this.SetActiveWorkspace(workspace);
    }
    private void ViewBollingerBands()
    {
      BollingerBandViewModel workspace = new BollingerBandViewModel();
      this.Workspaces.Add(workspace);
      AddMenuItem(workspace);
      this.SetActiveWorkspace(workspace);
    }
    private void ViewYieldCurve()
    {
      YieldCurveViewModel workspace = new YieldCurveViewModel();
      AddMenuItem(workspace);
      this.Workspaces.Add(workspace);
      this.SetActiveWorkspace(workspace);
    }
    private void ViewStochastics()
    {
      StochasticsViewModel workspace = new StochasticsViewModel();
      AddMenuItem(workspace);
      this.Workspaces.Add(workspace);
      this.SetActiveWorkspace(workspace);
    }
    private void ViewRSI()
    {
      RSIViewModel workspace = new RSIViewModel();
      AddMenuItem(workspace);
      this.Workspaces.Add(workspace);
      this.SetActiveWorkspace(workspace);
    }
    private void ViewGainLoss()
    {
      GainLossViewModel workspace = this.Workspaces.FirstOrDefault(vm => vm is GainLossViewModel) as GainLossViewModel;
      if (null == workspace)
      {
        workspace = new GainLossViewModel();
        workspace.WorkspaceInstantiator = InstantiateWorkspace;
        AddMenuItem(workspace);
        this.Workspaces.Add(workspace);
      }
      this.SetActiveWorkspace(workspace);
    }
    private void ViewTradeModels()
    {
      TradeModelViewModel workspace = this.Workspaces.FirstOrDefault(vm => vm is TradeModelViewModel) as TradeModelViewModel;
      if (null == workspace)
      {
        workspace = new TradeModelViewModel();
        AddMenuItem(workspace);
        this.Workspaces.Add(workspace);
      }
      this.SetActiveWorkspace(workspace);
    }
    private void ViewResistanceAndSupport()
    {
      ResistanceAndSupportViewModel workspace = this.Workspaces.FirstOrDefault(vm => vm is ResistanceAndSupportViewModel) as ResistanceAndSupportViewModel;
      if (null == workspace)
      {
        workspace = new ResistanceAndSupportViewModel();
        AddMenuItem(workspace);
        this.Workspaces.Add(workspace);
      }
      this.SetActiveWorkspace(workspace);
    }
    private void ViewMovingAverage()
    {
      MovingAverageViewModel workspace = new MovingAverageViewModel();
      AddMenuItem(workspace);
      this.Workspaces.Add(workspace);
      this.SetActiveWorkspace(workspace);
    }
    private void ViewMACD()
    {
      MACDViewModel workspace = new MACDViewModel();
      AddMenuItem(workspace);
      this.Workspaces.Add(workspace);
      this.SetActiveWorkspace(workspace);
    }
    private void ViewHistorical()
    {
      HistoricalViewModel workspace = this.Workspaces.FirstOrDefault(vm => vm is HistoricalViewModel) as HistoricalViewModel;
      if (null == workspace)
      {
        workspace = new HistoricalViewModel();
        AddMenuItem(workspace);
        this.Workspaces.Add(workspace);
      }
      this.SetActiveWorkspace(workspace);
    }
    private void ViewValuations()
    {
      ValuationsViewModel workspace = this.Workspaces.FirstOrDefault(vm => vm is ValuationsViewModel) as ValuationsViewModel;
      if (null == workspace)
      {
        workspace = new ValuationsViewModel();
        workspace.WorkspaceInstantiator = InstantiateWorkspace;
        AddMenuItem(workspace);
        this.Workspaces.Add(workspace);
      }
      this.SetActiveWorkspace(workspace);
    }
    private void ViewStickerPrice()
    {
      StickerPriceViewModel workspace = null;
      workspace = new StickerPriceViewModel();
      workspace.WorkspaceInstantiator = InstantiateWorkspace;
      AddMenuItem(workspace);
      this.Workspaces.Add(workspace);
      this.SetActiveWorkspace(workspace);
    }
    private void ViewDCFValuation()
    {
      DCFValuationViewModel workspace = null;
      workspace = new DCFValuationViewModel();
      workspace.WorkspaceInstantiator = InstantiateWorkspace;
      AddMenuItem(workspace);
      this.Workspaces.Add(workspace);
      this.SetActiveWorkspace(workspace);
    }
    private void ViewETFHoldings()
    {
      ETFHoldingViewModel workspace = this.Workspaces.FirstOrDefault(vm => vm is ETFHoldingViewModel) as ETFHoldingViewModel;
      if (null == workspace)
      {
        workspace = new ETFHoldingViewModel();
        workspace.WorkspaceInstantiator = InstantiateWorkspace;
        AddMenuItem(workspace);
        this.Workspaces.Add(workspace);
      }
      this.SetActiveWorkspace(workspace);
    }
    private void ViewPricing()
    {
      PricingViewModel workspace = new PricingViewModel();
      workspace.WorkspaceInstantiator = InstantiateWorkspace;
      AddMenuItem(workspace);
      this.Workspaces.Add(workspace);
      this.SetActiveWorkspace(workspace);
    }
    private void ViewHeadlines()
    {
      HeadlinesViewModel workspace = this.Workspaces.FirstOrDefault(vm => vm is HeadlinesViewModel) as HeadlinesViewModel;
      if(null==workspace)
      {
        workspace=new HeadlinesViewModel();
        workspace.WorkspaceInstantiator = InstantiateWorkspace;
        AddMenuItem(workspace);
        this.Workspaces.Add(workspace);
      }
      this.SetActiveWorkspace(workspace);
    }
    private void ViewSECFilings()
    {
      SECFilingViewModel workspace = new SECFilingViewModel();
      AddMenuItem(workspace);
      this.Workspaces.Add(workspace);
      this.SetActiveWorkspace(workspace);
    }
// ********************************************************************************
    private void SetActiveWorkspace(WorkspaceViewModel workspace)
    {
      if(!this.Workspaces.Contains(workspace))return;
      ICollectionView collectionView = CollectionViewSource.GetDefaultView(this.workspaces);
      if (null != collectionView) collectionView.MoveCurrentTo(workspace);
    }
  }
}
