using Avalonia;
using System;
using Microsoft.Extensions.Configuration;
using MarketData.Configuration;
using MarketData;
using System.Diagnostics;
using MarketData.DataAccess;

namespace PortfolioManager;

sealed class Program
{
  // Initialization code. Don't use any Avalonia, third-party APIs or any
  // SynchronizationContext-reliant code before AppMain is called: things aren't initialized
  // yet and stuff might break.
  [STAThread]
  public static void Main(string[] args)
  {
    MDTrace.LogLevel = LogLevel.VERBOSE;
    String strLogFile = "portfolio_manager.log";
    Trace.Listeners.Add(new TextWriterTraceListener(strLogFile));
    MDTrace.WriteLine(LogLevel.DEBUG, "[MAIN:STARTING]");

    IConfigurationBuilder builder = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: false);
    IConfigurationRoot configurationRoot = builder.Build();
    GlobalConfig.Instance.Configuration = configurationRoot;     // This call sets up configuration stuff so it needs to be first. 

    DataSourceEx portfolioData = MainDataSource.Instance.LocateDataSource("portfolio_data");
    DataSourceEx marketData = MainDataSource.Instance.LocateDataSource("market_data");
    DataSourceEx userData = MainDataSource.Instance.LocateDataSource("user_data");
    MDTrace.WriteLine(LogLevel.DEBUG,$"Using {portfolioData.Database} at {portfolioData.Datasource}");
    MDTrace.WriteLine(LogLevel.DEBUG,$"Using {marketData.Database} at {marketData.Datasource}");
    MDTrace.WriteLine(LogLevel.DEBUG,$"Using {userData.Database} at {userData.Datasource}");
    
    try
    {
      BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
    }
    catch (Exception exception)
    {
      MDTrace.WriteLine(LogLevel.DEBUG, exception.ToString());
    }

    ProcessThreadCollection currentThreads = Process.GetCurrentProcess().Threads;
    if (null != currentThreads && 0 != currentThreads.Count)
    {
      MDTrace.WriteLine(LogLevel.DEBUG, $"There were {currentThreads.Count} threads still running at application shutdown.");
    }
    MDTrace.WriteLine(LogLevel.DEBUG, "[MAIN:EXIT]");
    Environment.Exit(0);
  }

  // Avalonia configuration, don't remove; also used by visual designer.
  public static AppBuilder BuildAvaloniaApp()
      => AppBuilder.Configure<App>()
          .UsePlatformDetect()
          .WithInterFont()
          .LogToTrace();
}





