using HardwareData;
using HistoryUI.DataType;
using System.Collections.Concurrent;
using Universal;
namespace HistoryUI.ViewModels;

public partial class BaseViewModel<T_ResultType> : ObservableObject
{
    public BaseViewModel(Hardwares hardwares, IORM orm)
    {
        this._orm = orm;
        this.Hardwares = hardwares;

        if (StartSetting.ChannelIndex == 0 || StartSetting.Mini8Index == 0)
        {
            StartSetting.ChannelIndex = 1;
            StartSetting.Mini8Index = 1;
        }

        if (!hardwares.Mini8s.TryGetValue(StartSetting.Mini8Index, out var mini8) || mini8 is null)
            return;


        if (!hardwares.Mini8Channels.TryGetSubValue(StartSetting.Mini8Index, StartSetting.ChannelIndex, out ChannelData? channel) || channel is null)
            return;

        this.SelectedMini8 = new KeyValuePair<byte, Mini8Data>(StartSetting.Mini8Index, mini8);
        this.SelectedChannel = new KeyValuePair<byte, ChannelData>(StartSetting.ChannelIndex, channel);
        this.StartTime = DateTime.Now.AddMinutes(-20);
        this.EndTime = DateTime.Now;
    }

    protected IORM _orm;

    [ObservableProperty]
    private Hardwares _Hardwares;

    [ObservableProperty]
    private Dictionary<int, T_ResultType>? _Results;

    [ObservableProperty]
    private KeyValuePair<byte, Mini8Data>? _SelectedMini8;
    partial void OnSelectedMini8Changed(KeyValuePair<byte, Mini8Data>? value)
    {
        if (value is null)
            return;
        if (!this.Hardwares.Mini8Channels.TryGetValue(value.Value.Key, out var channels) || channels is null)
            return;

        this.Channels = channels;
    }
    [ObservableProperty]
    private KeyValuePair<byte, ChannelData>? _SelectedChannel;

    [ObservableProperty]
    private ConcurrentDictionary<byte, ChannelData>? _Channels;

    [ObservableProperty]
    private DateTime? _StartTime;

    [ObservableProperty]
    private DateTime? _EndTime;

    protected virtual void Query()
    {

    }

    protected bool QueryBase(out byte mini8, out byte channel)
    {
        mini8 = 0;
        channel = 0;
        if (this.SelectedChannel is null)
            return false;
        if (this.SelectedMini8 is null)
            return false;

        if (this.StartTime is null)
        {
            StartTime = DateTime.Now;
            StartTime = StartTime.Value.AddDays(-1);
        }

        this.EndTime ??= DateTime.Now;

        mini8 = this.SelectedMini8!.Value.Key;
        channel = this.SelectedChannel!.Value.Key;

        return true;
    }

    [RelayCommand]
    private void Exit()
    {
        App.Current.Shutdown();
    }
}
