using ConfigOperator;
using Mapster;

namespace HistoryUI.ViewModels;

public partial class LoadingViewModel : ObservableObject
{
    public LoadingViewModel(IEventAggregator eventAggregator, HardwareFileLoader hardwareFileLoader, IORM orm, BasicInfo basicInfo)
    {
        this.eventAggregator = eventAggregator;
        this.hardwareFileLoader = hardwareFileLoader;
        ProgressValue = 0;
        Task.Factory.StartNew(Init);
        this.orm = orm;
        this.basicInfo = basicInfo;
    }

    private readonly HardwareFileLoader hardwareFileLoader;
    private readonly IEventAggregator eventAggregator;
    private readonly IORM orm;
    private readonly BasicInfo basicInfo;

    private void Init()
    {

        if (!BaseConfigFileLoader.Load(out BasicInfo? basicInfo) ||
            basicInfo is null ||
            string.IsNullOrEmpty(basicInfo.DBConnectionString) ||
            string.IsNullOrEmpty(basicInfo.ServerAddress))
        {
            MessageBox.Show("Load BaseConfigFile file failed");
            App.Current.Dispatcher.InvokeShutdown();
            return;
        }
        basicInfo.Adapt(this.basicInfo);

        if (!LoadHardware())
        {
            MessageBox.Show("Load Config file failed");
            App.Current.Dispatcher.InvokeShutdown();
            return;
        }

        if (!orm.Initialize() || !orm.Open(basicInfo.DBConnectionString, ORM.DbType.PostgreSQL))
        {
            MessageBox.Show("Connect to Database Failed");
            App.Current.Dispatcher.InvokeShutdown();
        }

        if (string.IsNullOrEmpty(StartSetting.Content))
            return;

        eventAggregator.GetEvent<InitFinish>().Publish();
    }

    [RelayCommand]
    private void Select(string para)
    {
        StartSetting.Content = para;
        eventAggregator.GetEvent<InitFinish>().Publish();
    }

    [ObservableProperty]
    private string? _Test;

    [ObservableProperty]
    private double _ProgressValue;


    [ObservableProperty]
    private string? _Hint;

    private bool LoadHardware()
    {
        bool success = false; ;
        Application.Current.Dispatcher.Invoke(() =>
        {
            if (!this.hardwareFileLoader.Load())
                return;
            success = true;
        });

        return success;
    }
}
