using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Data.Core.Plugins;
using Avalonia.Markup.Xaml;
using Harmonia.Core.Extensions;
using Harmonia.UI.Caching;
using Harmonia.UI.Platform;
using Harmonia.UI.ViewModels;
using Harmonia.UI.Views;
using Microsoft.Extensions.DependencyInjection;
using System;

namespace Harmonia.UI;

public partial class App : Application
{
    public static IServiceProvider ServiceProvider { get; private set; }

    static App()
    {
        ServiceCollection services = new();

        services.AddSingleton<MainWindow>();

        services.AddSingleton<MainViewModel>();
        services.AddSingleton<PlaybackBarViewModel>();
        services.AddSingleton<PlayingSongInfoViewModel>();
        services.AddSingleton<PlaylistViewModel>();

        services.AddSingleton<IAudioBitmapCache, AudioBitmapCache>();
        services.AddSingleton<IStorageProviderLocator, StorageProviderLocator>();
        services.AddSingleton<IClipboardLocator, ClipboardLocator>();

        services.AddHarmonia();

        ServiceProvider = services.BuildServiceProvider();
    }

    public override void Initialize()
    {
        AvaloniaXamlLoader.Load(this);
    }

    public override void OnFrameworkInitializationCompleted()
    {
        // Line below is needed to remove Avalonia data validation.
        // Without this line you will get duplicate validations from both Avalonia and CT
        //BindingPlugins.DataValidators.RemoveAt(0);

        if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
        {
            //desktop.MainWindow = new MainWindow
            //{
            //    DataContext = new MainViewModel()
            //};

            desktop.MainWindow = ServiceProvider.GetRequiredService<MainWindow>();
        }
        else if (ApplicationLifetime is ISingleViewApplicationLifetime singleViewPlatform)
        {
            //singleViewPlatform.MainView = new MainView
            //{
            //    DataContext = new MainViewModel()
            //};

            singleViewPlatform.MainView = ServiceProvider.GetRequiredService<MainView>();
        }

        base.OnFrameworkInitializationCompleted();
    }
}