using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
using Logger;
using UIShare.UIViewModel;

namespace UIShare.GlobalVariable
{
    public static class ConfigService
    {
        private static readonly object _fileLock = new();
        /// <summary>
        /// 根据标题查询配置文件是否存在
        /// </summary>
        public static bool IsExit(string title)
        {
            if (string.IsNullOrEmpty(title))
            {
                return false;
            }

            string configPath = Path.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "ADP"), $"{title}.json");

            if (!File.Exists(configPath))
            {
                return false;
            }
            return true;
        }
        /// <summary>
        /// 根据标题（格子标识）加载独立的配置文件
        /// </summary>
        public static SystemConfig Load(string title)
        {
            if (string.IsNullOrEmpty(title))
            {
                throw new ArgumentException("配置标题不能为空", nameof(title));
            }

            // 临时实例化一个对象以获取默认的 SystemPath
            var dummy = new SystemConfig();
            string configPath = Path.Combine(dummy.SystemPath, $"{title}.json");

            if (!File.Exists(configPath))
            {
                // 如果不存在，创建一个带 Title 的默认配置并保存
                var defaultConfig = new SystemConfig { Title = title };
                EnsureDefaultCanDevice(defaultConfig);
                Save(defaultConfig);
                return defaultConfig;
            }

            lock (_fileLock)
            {
                try
                {
                    string json = File.ReadAllText(configPath);
                    var config = JsonConvert.DeserializeObject<SystemConfig>(json, new JsonSerializerSettings
                    {
                        TypeNameHandling = TypeNameHandling.All
                    });

                    config ??= new SystemConfig { Title = title };
                    EnsureDefaultCanDevice(config);
                    return config;
                }
                catch (Exception ex)
                {
                    LoggerHelper.ErrorWithNotify(title, $"格子 [{title}] 配置加载失败: {ex.Message}");
                    var fallback = new SystemConfig { Title = title };
                    EnsureDefaultCanDevice(fallback);
                    return fallback;
                }
            }
        }

        /// <summary>
        /// 保存指定的配置实例
        /// </summary>
        public static void Save(SystemConfig config)
        {
            if (config == null || string.IsNullOrEmpty(config.Title)) return;

            lock (_fileLock)
            {
                try
                {
                    if (!Directory.Exists(config.SystemPath))
                        Directory.CreateDirectory(config.SystemPath);

                    string configPath = Path.Combine(config.SystemPath, $"{config.Title}.json");

                    string json = JsonConvert.SerializeObject(config, Formatting.Indented, new JsonSerializerSettings
                    {
                        TypeNameHandling = TypeNameHandling.All
                    });

                    File.WriteAllText(configPath, json);
                    LoggerHelper.InfoWithNotify(config.Title, $"配置 [{config.Title}] 已保存。");
                }
                catch (Exception ex)
                {
                    LoggerHelper.ErrorWithNotify(config.Title, $"配置 [{config.Title}] 保存失败: {ex.Message}");
                }
            }
        }

        /// <summary>
        /// 确保配置中至少包含一个 CAN 设备（对应 SystemConfig.CANFD）。
        /// 旧配置或空配置会自动升级，使用户在设置界面能看到 CAN 设备。
        /// </summary>
        public static void EnsureDefaultCanDevice(SystemConfig config)
        {
            if (config.DeviceList == null)
            {
                config.DeviceList = new ObservableCollection<DeviceInfoVM>();
            }

            bool hasCan = config.DeviceList.Any(d =>
                string.Equals(d?.ConnectionType, "CAN", StringComparison.OrdinalIgnoreCase) ||
                string.Equals(d?.DeviceType, "ZLGCANFD", StringComparison.OrdinalIgnoreCase));

            if (!hasCan)
            {
                config.DeviceList.Add(new DeviceInfoVM
                {
                    DeviceName = "CAN",
                    DeviceType = "ZLGCANFD",
                    Remark = "周立功 CANFD 接口卡",
                    ConnectionType = "CAN",
                    IsEnabled = true,
                    IsConnected = false
                });
            }
        }
    }
}