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), "ACP"), $"{title}.json");

            if (!File.Exists(configPath))
            {
                return false;
            }
            return true;
        }
     
        /// <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>
        /// 保存全局配置
        /// </summary>
        public static void SaveGlobalConfig(GlobalConfig config)
        {
            if (config == null) return;

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

                    string configPath = Path.Combine(config.SystemPath, "GlobalConfig.json");

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

                    File.WriteAllText(configPath, json);

                }
                catch (Exception ex)
                {

                }
            }
        }

        /// <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
                });
            }
        }
    }
}