using BOB;
using Newtonsoft.Json;
using System;
using System.IO;

namespace ProcessManager
{
    public class JsonHelper
    {
        private static readonly object _lock = new();
        public static string SystemPath { get; set; } =
            Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "BOB");

        public static string ConfigFile;

        private static readonly JsonSerializerSettings jsonSettings = new()
        {
            TypeNameHandling = TypeNameHandling.All,  // 必须开启
            Formatting = Formatting.Indented,
            MetadataPropertyHandling = MetadataPropertyHandling.ReadAhead,
        };

        #region 配置保存
        public static void SaveToFile(SystemConfig config)
        {
            lock (_lock)
            {
                if (!Directory.Exists(SystemPath))
                    Directory.CreateDirectory(SystemPath);

                string json = JsonConvert.SerializeObject(config, jsonSettings);
                File.WriteAllText(ConfigFile, json);
            }
        }
        #endregion

        #region 配置加载
        public static SystemConfig LoadFromFile()
        {
            lock (_lock)
            {
                if (!File.Exists(ConfigFile))
                {
                    throw new Exception("没找到系统配置文件");
                }

                try
                {
                    string json = File.ReadAllText(ConfigFile);
                    return JsonConvert.DeserializeObject<SystemConfig>(json, jsonSettings);
                }
                catch (Exception ex)
                {
                    // 如果反序列化失败，避免程序崩溃
                    throw new Exception("系统配置加载失败: " + ex.Message);
                }
            }
        }
        #endregion
    }
}
