using System;
using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Data.Core;
using Avalonia.Data.Core.Plugins;
using System.Linq;
using Avalonia.Markup.Xaml;
using AvaloniaSideBarEx.ViewModels;
using AvaloniaSideBarEx.Views;
using Microsoft.Extensions.DependencyInjection;

namespace AvaloniaSideBarEx;

public partial class App : Application
{
    // 定義 ServiceProvider
    public IServiceProvider? Services { get; set; }
    
    public override void Initialize()
    {
        AvaloniaXamlLoader.Load(this);
    }

    public override void OnFrameworkInitializationCompleted()
    {
        // 初始化 DI 容器
        var collection = new ServiceCollection();
        
        // 註冊 ViewModels
        collection.AddSingleton<MainWindowViewModel>();
        collection.AddSingleton<HomeViewModel>(); 
        collection.AddSingleton<SettingsViewModel>();
        collection.AddSingleton<AboutViewModel>();

        // 建立 Provider
        Services = collection.BuildServiceProvider();
        
        if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
        {
            // 解析 MainWindow 並注入 ViewModel
            var mainVm = Services.GetRequiredService<MainWindowViewModel>();
            DisableAvaloniaDataAnnotationValidation();
            desktop.MainWindow = new MainWindow
            {
                DataContext = mainVm
            };
        }

        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);
        }
    }
}