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

namespace StandardScene.Charge
{
    /// <summary>
    /// 充电策略配置服务（单例模式）
    /// </summary>
    public class ChargeStrategyConfigService
    {
        private static ChargeStrategyConfigService _instance;
        private static readonly object _lock = new object();
        private readonly string configFilePath;
        private const string ConfigFileName = "ChargeStrategyConfig.json";

        /// <summary>
        /// 获取单例实例
        /// </summary>
        public static ChargeStrategyConfigService Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_lock)
                    {
                        if (_instance == null)
                        {
                            _instance = new ChargeStrategyConfigService();
                        }
                    }
                }
                return _instance;
            }
        }

        private ChargeStrategyConfigService()
        {
            // 配置文件保存在应用程序目录下的 Config 文件夹
            string configDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config");
            
            // 确保目录存在
            if (!Directory.Exists(configDir))
            {
                Directory.CreateDirectory(configDir);
            }

            configFilePath = Path.Combine(configDir, ConfigFileName);
        }

        /// <summary>
        /// 加载配置
        /// </summary>
        public ChargeStrategyConfig LoadConfig()
        {
            try
            {
                if (File.Exists(configFilePath))
                {
                    string json = File.ReadAllText(configFilePath);
                    var config = JsonConvert.DeserializeObject<ChargeStrategyConfig>(json);
                    
                    // 验证配置
                    if (config.Validate(out string errorMessage))
                    {
                        return config;
                    }
                    else
                    {
                        // 配置无效，返回默认配置
                        System.Diagnostics.Debug.WriteLine($"配置验证失败: {errorMessage}，使用默认配置");
                        return ChargeStrategyConfig.CreateDefault();
                    }
                }
                else
                {
                    // 文件不存在，创建默认配置并保存
                    var defaultConfig = ChargeStrategyConfig.CreateDefault();
                    SaveConfig(defaultConfig);
                    return defaultConfig;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"加载配置失败: {ex.Message}");
                // 加载失败，返回默认配置
                return ChargeStrategyConfig.CreateDefault();
            }
        }

        /// <summary>
        /// 保存配置
        /// </summary>
        public void SaveConfig(ChargeStrategyConfig config)
        {
            try
            {
                // 验证配置
                if (!config.Validate(out string errorMessage))
                {
                    throw new InvalidOperationException($"配置验证失败: {errorMessage}");
                }

                // 序列化为 JSON
                string json = JsonConvert.SerializeObject(config, Formatting.Indented);
                
                // 保存到文件
                File.WriteAllText(configFilePath, json);
                
                System.Diagnostics.Debug.WriteLine($"配置保存成功: {configFilePath}");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"保存配置失败: {ex.Message}");
                throw new Exception($"保存配置失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 获取配置文件路径
        /// </summary>
        public string GetConfigFilePath()
        {
            return configFilePath;
        }

        /// <summary>
        /// 检查配置文件是否存在
        /// </summary>
        public bool ConfigFileExists()
        {
            return File.Exists(configFilePath);
        }

        /// <summary>
        /// 删除配置文件
        /// </summary>
        public void DeleteConfig()
        {
            try
            {
                if (File.Exists(configFilePath))
                {
                    File.Delete(configFilePath);
                    System.Diagnostics.Debug.WriteLine($"配置文件已删除: {configFilePath}");
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"删除配置文件失败: {ex.Message}");
                throw new Exception($"删除配置文件失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 导出配置到指定路径
        /// </summary>
        public void ExportConfig(string exportPath, ChargeStrategyConfig config)
        {
            try
            {
                string json = JsonConvert.SerializeObject(config, Formatting.Indented);
                File.WriteAllText(exportPath, json);
                System.Diagnostics.Debug.WriteLine($"配置导出成功: {exportPath}");
            }
            catch (Exception ex)
            {
                throw new Exception($"导出配置失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 从指定路径导入配置
        /// </summary>
        public ChargeStrategyConfig ImportConfig(string importPath)
        {
            try
            {
                if (!File.Exists(importPath))
                {
                    throw new FileNotFoundException($"配置文件不存在: {importPath}");
                }

                string json = File.ReadAllText(importPath);
                var config = JsonConvert.DeserializeObject<ChargeStrategyConfig>(json);

                // 验证配置
                if (!config.Validate(out string errorMessage))
                {
                    throw new InvalidOperationException($"配置验证失败: {errorMessage}");
                }

                return config;
            }
            catch (Exception ex)
            {
                throw new Exception($"导入配置失败: {ex.Message}", ex);
            }
        }
    }
}

