namespace HistoryView.ViewModels.Dialogs;

public partial class ConfigEditorViewModel(HubSender hubSender) : ObservableObject, IDialogAware
{
    public DialogCloseListener RequestClose { get; set; }

    [ObservableProperty]
    private TempConfig? _File;

    [ObservableProperty]
    private Visibility _Loading;


    public bool CanCloseDialog()
    {

        return true;
    }

    public void OnDialogClosed()
    {
    }

    public void OnDialogOpened(IDialogParameters parameters)
    {
        this.Loading = Visibility.Visible;
        if (!parameters.TryGetValue("ConfigEditor", out TempConfig? tempConfig) || tempConfig is null)
        {
            this.RequestClose.Invoke();
            return;
        }
        Task.Factory.StartNew(() =>
        {
            App.Current.Dispatcher.Invoke(() =>
            {
                this.File = new();
                tempConfig.Adapt(this.File);
                this.Loading = Visibility.Collapsed;
            });
        });
    }

    [RelayCommand]
    private void Save(string mode)
    {
        if (this.File is null)
            return;

        _ = mode switch
        {
            "save" => hubSender.SaveConfig(this.File.ConfigName, this.File, false),
            "saveas" => hubSender.SaveConfig(this.File.ConfigName, this.File, true),
            _ => false
        };

        this.RequestClose.Invoke();
    }

    [RelayCommand]
    private void Exit()
    {
        this.RequestClose.Invoke();
    }
}