using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SWRIS.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;

namespace SWRIS.Core
{
    public class ConfigHelper
    {
        public static readonly string AesKey = "mhSnwPLLL5T6ITmLJQogp3et5U2gYw5wiLtdZaZajRU="; // 32字节的Base64字符串
        public static readonly string AesIV = "Z/stNJl+kA7G02oBlpeERA==";  // 16字节的Base64字符串
        private static readonly string filePath = AppDomain.CurrentDomain.BaseDirectory + "Config/config.json";
        private static readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
        private const int LockTimeout = 5000; // 5秒超时

        public static ConfigModel Read()
        {
            try
            {
                if (!_lock.TryEnterReadLock(LockTimeout))
                {
                    LogHelper.Error("获取读取锁超时！");
                    return null;
                }

                try
                {
                    if (File.Exists(filePath))
                    {
                        using (StreamReader r = new StreamReader(filePath))
                        {
                            var json = r.ReadToEnd();
                            var config = JsonConvert.DeserializeObject<ConfigModel>(json);
                            if (config.Calibration.Tcp == null)
                            {
                                config.Calibration.Tcp = new TcpSettings();
                            }
                            if (config.Calibration.Serial == null)
                            {
                                config.Calibration.Serial = new SerialSettings();
                            }
                            if (config.Calibration.Limits == null)
                            {
                                config.Calibration.Limits = new List<LimitData> { new LimitData(), new LimitData() };
                            }
                            else
                            {
                                // 补充缺少的元素
                                while (config.Calibration.Limits.Count < 2)
                                {
                                    config.Calibration.Limits.Add(new LimitData());
                                }
                            }
                            return config;
                        }
                    }
                    return null;
                }
                finally
                {
                    _lock.ExitReadLock();
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error("读取配置文件失败！", ex);
                return null;
            }
        }

        public static bool Set(ConfigModel config)
        {
            try
            {
                if (!_lock.TryEnterWriteLock(LockTimeout))
                {
                    LogHelper.Error("获取写入锁超时！");
                    return false;
                }

                try
                {
                    string jsonData = JsonConvert.SerializeObject(config, Formatting.Indented);
                    File.WriteAllText(filePath, jsonData);
                    return true;
                }
                finally
                {
                    _lock.ExitWriteLock();
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error("保存配置文件失败！", ex);
                return false;
            }
        }

        public static bool SetEquipment(EquipmentModel equipmentData)
        {
            // 参数检查
            if (equipmentData == null || equipmentData.Parameter == null || string.IsNullOrEmpty(equipmentData.IpAddress))
            {
                return false;
            }

            try
            {
                // 获取写入锁
                if (!_lock.TryEnterWriteLock(LockTimeout))
                {
                    LogHelper.Error("获取写入锁超时！");
                    return false;
                }

                try
                {
                    // 检查文件是否存在
                    if (!File.Exists(filePath))
                    {
                        return false;
                    }

                    // 读取JSON文件
                    JObject jsonObject;
                    using (StreamReader reader = File.OpenText(filePath))
                    using (JsonTextReader jsonTextReader = new JsonTextReader(reader))
                    {
                        jsonObject = (JObject)JToken.ReadFrom(jsonTextReader);
                    }

                    // 获取设备数组
                    if (!(jsonObject["Equipments"] is JArray equipments)) return false;

                    // 查找要修改的设备
                    var targetEquipment = equipments.FirstOrDefault(c =>
                        c["IpAddress"] != null &&
                        c["IpAddress"].ToString() == equipmentData.IpAddress);

                    if (targetEquipment == null) return false;

                    // 关键修改点：先移除旧设备，再添加新设备
                    equipments.Remove(targetEquipment);
                    equipments.Add(JObject.FromObject(equipmentData));

                    string output = JsonConvert.SerializeObject(jsonObject, Formatting.Indented);
                    File.WriteAllText(filePath, output);
                    return true;
                }
                finally
                {
                    _lock.ExitWriteLock();
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error("保存配置文件失败！", ex);
                return false;
            }
        }
    }
}