using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Data.Core;
using Avalonia.Data.Core.Plugins;
using System.Linq;
using Avalonia.Markup.Xaml;
using PortfolioManager.ViewModels;
using PortfolioManager.Views;
using System;
using System.ComponentModel;
using Avalonia.Controls;
using Axiom.Utils;

namespace PortfolioManager;

public partial class App : Application
{
    public override void Initialize()
    {
        AvaloniaXamlLoader.Load(this);
    }

    public override void OnFrameworkInitializationCompleted()
    {
      if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
      {
        // Avoid duplicate validations from both Avalonia and the CommunityToolkit. 
        // More info: https://docs.avaloniaui.net/docs/guides/development-guides/data-validation#manage-validationplugins
        DisableAvaloniaDataAnnotationValidation();
        MainWindowViewModel mainWindowViewModel = new MainWindowViewModel();
        desktop.MainWindow = new MainWindow
        {
          DataContext = mainWindowViewModel,
        };

        EventHandler requestCloseHandler = null;
        requestCloseHandler = delegate
        {
          MDTrace.WriteLine(LogLevel.DEBUG, "App: Received RequestCloseHandler event");
          if (null != mainWindowViewModel)
          {
            mainWindowViewModel.RequestClose -= requestCloseHandler;
            mainWindowViewModel.Dispose();
            mainWindowViewModel = null;
          }
          if (null != desktop.MainWindow)
          {
            desktop.MainWindow.Close();
            MDTrace.WriteLine(LogLevel.DEBUG, "App: Shutting down the desktop");
            desktop.Shutdown();
            desktop.MainWindow = null;
          }
        };
        mainWindowViewModel.RequestClose += requestCloseHandler;

        EventHandler<WindowClosingEventArgs> closingHandler = null;
        closingHandler = delegate
        {
          MDTrace.WriteLine(LogLevel.DEBUG, "App: Received ClosingHandler event");
          if (null != mainWindowViewModel)
          {
            mainWindowViewModel.Dispose();
          }
        };
        desktop.MainWindow.Closing += closingHandler;
      }
      base.OnFrameworkInitializationCompleted();
    }

    private void DisableAvaloniaDataAnnotationValidation()
    {
        // Get an array of plugins to remove
        var dataValidationPluginsToRemove =
            BindingPlugins.DataValidators.OfType<DataAnnotationsValidationPlugin>().ToArray();

        // remove each entry found
        foreach (var plugin in dataValidationPluginsToRemove)
        {
            BindingPlugins.DataValidators.Remove(plugin);
        }
    }
}