using BOB.Models;
using Logger;
using Model;
using Newtonsoft.Json;
using System.Collections.ObjectModel;
using System.IO;
using System.Reflection;

namespace BOB
{
    public class SystemConfig
    {
        private static readonly object _lock = new();

        private static SystemConfig? _instance;

        public static SystemConfig Instance
        {
            get
            {
                lock (_lock)
                {
                    if (_instance == null)
                    {
                        _instance = new();
                        _instance.LoadFromFile();
                    }
                    return _instance;
                }
            }
        }

        [JsonIgnore]
        public string SystemPath { get; set; } = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "BOB");
        public string Title { get; set; } = "";
        public int SaveDay { get; set; }
        public string DBSavePath { get; set; } = "";

        public int PerformanceLevel { get; set; } = 50;

        public string DLLFilePath { get; set; } = @"D:\BOB\指令\";

        public string SubProgramFilePath { get; set; } = @"D:\BOB\子程序\";

        public string DefaultSubProgramFilePath { get; set; } = "";
        public ObservableCollection<string> CurSingleList { get; set; }
        public List<DeviceConfigModel> DeviceList { get; set; } = new();

        #region  配置加载方法
        public void SaveToFile()
        {
            lock (_lock)
            {
                try
                {
                    if (!Directory.Exists(SystemPath))
                        Directory.CreateDirectory(SystemPath);

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

                    // 支持接口多态序列化
                    string json = JsonConvert.SerializeObject(this, Formatting.Indented,
                        new JsonSerializerSettings
                        {
                            TypeNameHandling = TypeNameHandling.All
                        });

                    File.WriteAllText(configPath, json);

                    LoggerHelper.InfoWithNotify("系统配置已保存。");
                }
                catch (Exception ex)
                {
                    LoggerHelper.ErrorWithNotify($"配置保存失败: {ex.Message}");
                }
            }
        }

        public void LoadFromFile()
        {
            string configPath = Path.Combine(SystemPath, $"{Title}.json");
            if(Title == "")
            {
                return;
            }
            if (!File.Exists(configPath))
            {
                SaveToFile();
                return;
            }

            try
            {
                string json = File.ReadAllText(configPath);

                // 支持接口多态反序列化
                var loadedConfig = JsonConvert.DeserializeObject<SystemConfig>(json,
                    new JsonSerializerSettings
                    {
                        TypeNameHandling = TypeNameHandling.All
                    });

                // 复制所有可写属性（排除 JsonIgnore 属性）
                PropertyInfo[] properties = typeof(SystemConfig).GetProperties();
                foreach (var prop in properties)
                {
                    if (prop.CanWrite && !Attribute.IsDefined(prop, typeof(JsonIgnoreAttribute)))
                    {
                        prop.SetValue(this, prop.GetValue(loadedConfig));
                    }
                }
            }
            catch (Exception ex)
            {
                LoggerHelper.ErrorWithNotify($"配置加载失败: {ex.Message}", ex.StackTrace);
            }
        }
       
        #endregion
    }
}