using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using EEMSClientCore;
using EEMSUIClient.Models;
using EEMSUIClient.Services;
using GeneralData;
using Microsoft.Win32;
using System.IO;
using System.Text.Json;
using System.Windows;

namespace EEMSUIClient.ViewModels;

public partial class MainWindowViewModel : ObservableObject
{
    private readonly IClientService _clientService;

    private readonly string _settingsFolder = $"{Environment.CurrentDirectory}/Settings";
    private readonly string _ipAddressFileName = "IpAddressInformation.json";
    private readonly string _deviceInfoFileName = "DeviceInformation.json";

    private int _count;
    private Dictionary<string, object> _realtimeData = [];

    [ObservableProperty]
    private string _ipAddress = string.Empty;

    [ObservableProperty]
    private string _port = string.Empty;

    [ObservableProperty]
    private string _hubName = string.Empty;

    [ObservableProperty]
    [NotifyPropertyChangedFor(nameof(IsNotConnected))]
    private bool _isConnected;

    [ObservableProperty]
    private string _selectedRecipeDict=string.Empty;

    [ObservableProperty]
    private string _selectedConfigDict = string.Empty;

    [ObservableProperty]
    private string[] _deviceModels = Enum.GetNames(typeof(DeviceModel));

    [ObservableProperty]
    private string _deviceModel = string.Empty;

    [ObservableProperty]
    private int _deviceModelIndex = -1;

    [ObservableProperty]
    private string _deviceSubModel = string.Empty;

    [ObservableProperty]
    private string _deviceName = string.Empty;

    [ObservableProperty]
    private string _position = string.Empty;

    [ObservableProperty]
    private string _softwareVersion = string.Empty;

    [ObservableProperty]
    private string _dBConnectionString = string.Empty;

    [ObservableProperty]
    private string _guidStr = string.Empty;

    public MainWindowViewModel(IClientService clientService)
    {
        _clientService = clientService;

        Initialize();
    }

    public bool IsNotConnected => !IsConnected;

    [RelayCommand]
    private void SelectRecipe()
    {
        var dialog = new OpenFolderDialog()
        {
            Title = "Select Folder"
        };
        if (dialog.ShowDialog() == true)
        {
            SelectedRecipeDict = dialog.FolderName;
            var service = (IClientBaseProvider)_clientService;
            service.RecipePath = SelectedRecipeDict;
        }
    }

    [RelayCommand]
    private void SelectConfig()
    {
        var dialog = new OpenFolderDialog()
        {
            Title = "Select Folder"
        };
        if (dialog.ShowDialog() == true)
        {
            SelectedConfigDict = dialog.FolderName;
            var service = (IClientBaseProvider)_clientService;
            service.ConfigPath = SelectedConfigDict;
        }
    }

    [RelayCommand]
    private void Connect()
    {
        if (string.IsNullOrWhiteSpace(IpAddress) || string.IsNullOrWhiteSpace(Port) || string.IsNullOrWhiteSpace(HubName))
        {
            MessageBox.Show("存在未被填写的项目！");
            //log
            return;
        }

        if (!_clientService.Initialize(IpAddress, int.Parse(Port), HubName))
        {
            MessageBox.Show("初始化失败！");
            //log
            return;
        }

        IsConnected = true;

        var addressInfo = new AddressInfo()
        {
            Ip= IpAddress,
            Port=int.Parse(Port),
            HubName=HubName,
        };

        string jsonString = JsonSerializer.Serialize(addressInfo);
        File.WriteAllText(Path.Combine(_settingsFolder, _ipAddressFileName), jsonString);
    }

    [RelayCommand]
    private void Register()
    {
        if (string.IsNullOrWhiteSpace(DeviceModel) ||
            string.IsNullOrWhiteSpace(DeviceSubModel) ||
            string.IsNullOrWhiteSpace(DeviceName) ||
            string.IsNullOrWhiteSpace(Position) ||
            string.IsNullOrWhiteSpace(SoftwareVersion) ||
            string.IsNullOrWhiteSpace(DBConnectionString))
        {
            MessageBox.Show("存在未被填写的项目！");
            return;
        }

        try
        {
            _ = Enum.TryParse<DeviceModel>(DeviceModel, out var deviceModel);
            var rst=Guid.TryParse(GuidStr, out var guidRst);
            var deviceInfo = new Models.DeviceInfo
            {
                DeviceModel = deviceModel,
                DeviceSubModel = DeviceSubModel,
                DeviceName = DeviceName,
                Position = Position,
                Guid = rst ? guidRst : null,
                SoftwareVersion = SoftwareVersion,
                DBConnectionString = DBConnectionString
            };

            var guid = _clientService.RegisterDevice(deviceInfo);
            if (guid == Guid.Empty)
            {
                MessageBox.Show("未能获取Guid，设备注册失败！");
                return;
            }

            GuidStr = guid.ToString();
            MessageBox.Show("设备注册成功。");
            deviceInfo.Guid = guid;
            var jsonString = JsonSerializer.Serialize(deviceInfo);
            File.WriteAllText(Path.Combine(_settingsFolder, _deviceInfoFileName), jsonString);
        }
        catch (Exception ex)
        {
            MessageBox.Show($"遭遇异常：{ex.Message}");
        }
    }

    [RelayCommand]
    private void Trigger()
    {
        try
        {
            _realtimeData.Clear();
            for (int i = 0; i < 10; i++)
            {
                _realtimeData[i.ToString()] = DateTime.Now.ToString();
            }
            _clientService.UpdateRealTimeData(_realtimeData);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void Initialize()
    {
        if (!Directory.Exists(_settingsFolder))
        {
            Directory.CreateDirectory(_settingsFolder);
        }

        var ipAddressFilePath = Path.Combine(_settingsFolder, _ipAddressFileName);
        if (Path.Exists(ipAddressFilePath))
        {
            string jsonFromFile = File.ReadAllText(ipAddressFilePath);
            var deserializedAddressInfo = JsonSerializer.Deserialize<AddressInfo>(jsonFromFile);
            if (deserializedAddressInfo is not null)
            {
                IpAddress = deserializedAddressInfo.Ip;
                Port = deserializedAddressInfo.Port.ToString();
                HubName = deserializedAddressInfo.HubName;
            }
        }

        var deviceInfoFilePath = Path.Combine(_settingsFolder, _deviceInfoFileName);
        if (Path.Exists(deviceInfoFilePath))
        {
            string jsonFromFile = File.ReadAllText(deviceInfoFilePath);
            var deserializedDeviceInfo = JsonSerializer.Deserialize<DeviceInfo>(jsonFromFile);
            if (deserializedDeviceInfo is not null)
            {
                DeviceModelIndex = (int)deserializedDeviceInfo.DeviceModel!;
                DeviceModel = deserializedDeviceInfo.DeviceModel.ToString() ?? string.Empty;
                DeviceSubModel = deserializedDeviceInfo.DeviceSubModel ?? string.Empty;
                DeviceName = deserializedDeviceInfo.DeviceName ?? string.Empty;
                Position = deserializedDeviceInfo.Position ?? string.Empty;
                SoftwareVersion = deserializedDeviceInfo.SoftwareVersion ?? string.Empty;
                GuidStr = deserializedDeviceInfo.Guid.ToString() ?? string.Empty;
                DBConnectionString = deserializedDeviceInfo.DBConnectionString ?? string.Empty;
            }
        }
    }
}
