using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows;
using System.Globalization;
using System.Windows.Markup;
using System.ComponentModel;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using Forms=System.Windows.Forms;
using TradeBlotter.ViewModels;
using MarketData;
using TradeBlotter.UIUtils;
using MarketData.Cache;
using TradeBlotter.Cache;

namespace TradeBlotter
{
  /// <summary>
  /// Interaction logic for App.xaml
  /// </summary>
  public partial class App : Application
  {
    static App()
    {
      FrameworkElement.LanguageProperty.OverrideMetadata(typeof(FrameworkElement),new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));
    }
    protected override void OnStartup(StartupEventArgs e)
    {

      try
      {
        MDTrace.LogLevel = LogLevel.VERBOSE;
        String strLogFile = "enavigator.log";
        Trace.Listeners.Add(new TextWriterTraceListener(strLogFile));
        MDTrace.WriteLine(LogLevel.DEBUG, "[STARTING]");

        AppDomain currentDomain = AppDomain.CurrentDomain;
        currentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionHandler);


        WebBrowserHelper.SetWebBrowserCompatibility();    // This is to prevent the webbrowser control from popping up compatibility messagebox while browsing the SEC filings.  
        base.OnStartup(e);
        MainWindow mainWindow = new MainWindow();
        MainWindowViewModel mainWindowViewModel = new MainWindowViewModel();   
        EventHandler handler = null;
        handler = delegate
        {
          if(null!=mainWindowViewModel)
          {
            mainWindowViewModel.RequestClose -= handler;
            mainWindowViewModel.Dispose();
            mainWindowViewModel = null;
          }
          if(null!=mainWindow)
          {
            mainWindow.Close();
            mainWindow = null;
          }
        };
        mainWindowViewModel.RequestClose+=handler;
        mainWindow.DataContext=mainWindowViewModel;
        CancelEventHandler closingEventHandler = null;
        closingEventHandler = delegate
        {
          if (null != mainWindowViewModel)
          {
            mainWindowViewModel.RequestClose -= handler;
            mainWindowViewModel.Dispose();
            mainWindowViewModel = null;
          }
        };
        mainWindow.Closing += closingEventHandler;
        mainWindow.Show();
        mainWindow.WindowState=WindowState.Maximized;
        CreateFloatingWindow(mainWindow);
        mainWindow.Focus();
      }
      catch(Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,String.Format("Exception:{0}",exception.ToString()));
        MessageBox.Show(String.Format("An exception was encountered.  Please check the log file.  The application will now exit. {0}",exception.ToString()));
      }
    }
// The caches are disposed in the MainWindowViewModel::OnDispose()
    protected override void OnExit(ExitEventArgs e)
    {
      //try{LocalPriceCache.GetInstance().Dispose();}catch(Exception){;}
      //try{GBPriceCache.GetInstance().Dispose();}catch(Exception){;}
      //try{PriceCache.GetInstance().Dispose();}catch(Exception){;}
//      DividendHistoryCache.GetInstance().Dispose();
    }
    void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs eventArgs)
    {
      MDTrace.WriteLine(LogLevel.DEBUG, String.Format("App.Xaml.cs->UnhandledExceptionHandler()"));
      string errorMessage = string.Format("An unhandled exception occurred: {0}", eventArgs.ExceptionObject);
      MDTrace.WriteLine(LogLevel.DEBUG, String.Format("Exception:{0}", errorMessage));
    }
    //void OnDispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs eventArgs)
    //{
    //  string errorMessage = string.Format("An unhandled exception occurred: {0}", eventArgs.Exception.Message);
    //  MDTrace.WriteLine(LogLevel.DEBUG, String.Format("Exception:{0}", errorMessage));
    //  eventArgs.Handled = true;
    //}
    private static void CreateFloatingWindow(Window parentWindow)
    {
      String launchTicker=ConfigurationManager.AppSettings["LaunchTickerView"];
      if(null==launchTicker)return;
      launchTicker=launchTicker.ToLower();
      if(launchTicker.Equals("false"))return;
      FloatingWindow floatingWindow=new FloatingWindow();
      floatingWindow.Width=SystemParameters.VirtualScreenWidth;
      floatingWindow.Top=(SystemParameters.VirtualScreenTop+SystemParameters.VirtualScreenHeight)-floatingWindow.Height;
      floatingWindow.Left=0;
      floatingWindow.Topmost=true;
      FloatingWindowViewModel floatingWindowViewModel=new FloatingWindowViewModel(floatingWindow.LayoutRoot);
      floatingWindow.DataContext=floatingWindowViewModel;
      parentWindow.Closing+=delegate
      {
        floatingWindowViewModel.Dispose();
        floatingWindow.Close();
      };
      floatingWindow.Show();
    }
  }
}
