using AlarmInfoServerSim.Services;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using ConfigOperator;
using HardwareData;
using RealtimeData;
using RTCommunicatorBase;
using System.Collections.Concurrent;
using System.IO;

namespace AlarmInfoServerSim.ViewModels
{
    public partial class WorkAreaViewModel : ObservableObject
    {
        private readonly IInfoSendingService _infoSendingService;

        private readonly Hardwares _hardwares;

        [ObservableProperty]
        private ConcurrentDictionary<byte, Mini8Data> _mini8;

        [ObservableProperty]
        private int _selectedMini8Index = -1;

        [ObservableProperty]
        private ConcurrentDictionary<byte, ChannelData> _mini8Channel;

        [ObservableProperty]
        private int _selectedChannelIndex = -1;

        [ObservableProperty]
        private AlarmType[] _alarmTypes;

        [ObservableProperty]
        private int _selectedAlarmTypeIndex = -1;

        [ObservableProperty]
        private float _pV;

        [ObservableProperty]
        private float _caps;

        [ObservableProperty]
        private float _floor;

        public WorkAreaViewModel(IInfoSendingService infoSendingService)
        {
            _infoSendingService = infoSendingService;

            _hardwares = new Hardwares();
            HardwareFileLoader hardwareFileLoader = new HardwareFileLoader(_hardwares);
            string folderPath = Path.Combine(new DirectoryInfo(Paths.LocalPath!)!.Parent!.Parent!.FullName, "Settings", "Hardwares");

            _mini8 = hardwareFileLoader.Load(folderPath) ? _hardwares.Mini8s : [];
            _mini8Channel = [];

            _alarmTypes = Enum.GetValues<AlarmType>();
        }

        

        partial void OnSelectedMini8IndexChanged(int value)
        {
            SelectedChannelIndex = -1;
            SelectedAlarmTypeIndex = -1;
            var index = Mini8.ElementAt(value).Key;
            Mini8Channel = _hardwares.Mini8Channels[index];
        }

        partial void OnSelectedChannelIndexChanged(int value)
        {
            SelectedAlarmTypeIndex = -1;
        }

        [RelayCommand]
        private void SendInfo()
        {
            if (SelectedMini8Index > -1 && SelectedChannelIndex > -1 && SelectedAlarmTypeIndex > -1)
            {
                // ChannelAlarmNotify = 1
                _infoSendingService.Send(1, new ST_ALARM()
                {
                    Mini8Index = Mini8.ElementAt(SelectedMini8Index).Key,
                    ChannelIndex = Mini8Channel.ElementAt(SelectedChannelIndex).Key,
                    PV = PV,
                    Caps = Caps,
                    Floor = Floor,
                    AlarmType = (AlarmType)SelectedAlarmTypeIndex
                });
            }
        }
    }
}
