namespace MinicsUI.ViewModels.Dialogs;

public partial class TraceLogViewModel(Hardwares hardwares, DialogService dialogService) : ObservableObject, IDialogAwareTitle
{
    public DialogCloseListener RequestClose { get; set; }
    public string Title { get; set; } = "";

    [ObservableProperty]
    private string? _Hint;

    [ObservableProperty]
    private Visibility _HintVis = Visibility.Collapsed;

    [ObservableProperty]
    private ObservableCollection<Selector> _Selecters = [];

    [ObservableProperty]
    private ObservableDictionary<byte, Channel> _Channels = [];

    [ObservableProperty]
    private ObservableDictionary<string, RealtimeDataPlotHelper> _PlotHelpers = [];

    public bool CanCloseDialog()
    {
        return true;
    }

    public void OnDialogClosed()
    {
        foreach (var item in this.PlotHelpers.Values)
            item.Dispose();
    }

    public void OnDialogOpened(IDialogParameters parameters)
    {
        if (!parameters.TryGetValue("Mini8Info", out Mini8Info? mini8) || mini8 is null)
            return;

        if (!hardwares.Mini8Channels.TryGetValue(mini8.Index, out ObservableDictionary<byte, Channel>? channels) || channels is null)
            return;

        this.Channels = channels;
        this.Selecters ??= [];
        this.PlotHelpers ??= [];

        foreach (var channel in channels.Values)
        {
            this.Selecters.Add(new(channel));
            if (channel.Inhibit == Inhibit.Disable)
                continue;
            RealtimeDataPlotHelper helper = new();
            helper.InitPlot(channel);
            this.PlotHelpers[channel.Name!] = helper;
        }

    }


    [RelayCommand]
    private void EditChannel(Channel channel)
    {
        DialogParameters para = new()
        {
            { "Channel", channel },
        };

        dialogService.Show("Channel", para, null);
    }

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