using Microsoft.Maui.Storage;
using System.Text.Json;
using Hua.Todo.Maui.Models;

namespace Hua.Todo.Maui.Services
{
    /// <summary>
    /// 热键设置服务接口
    /// </summary>
    public interface IHotKeySettingsService
    {
        /// <summary>
        /// 获取热键配置
        /// </summary>
        HotKeyConfig GetConfig();

        /// <summary>
        /// 保存热键配置
        /// </summary>
        void SaveConfig(HotKeyConfig config);

        /// <summary>
        /// 重置为默认配置
        /// </summary>
        void ResetToDefault();
    }

    /// <summary>
    /// 热键设置服务实现，使用 Preferences 存储配置
    /// </summary>
    public class HotKeySettingsService : IHotKeySettingsService
    {
        private const string SettingsKey = "HotKeyConfig";
        private readonly AppSettings _appSettings;

        public HotKeySettingsService(AppSettings appSettings)
        {
            _appSettings = appSettings;
        }

        /// <summary>
        /// 获取当前热键配置，如果不存在则返回默认配置
        /// </summary>
        public HotKeyConfig GetConfig()
        {
            var json = Preferences.Get(SettingsKey, string.Empty);
            if (string.IsNullOrEmpty(json))
            {
                return GetDefaultConfig();
            }

            try
            {
                return JsonSerializer.Deserialize<HotKeyConfig>(json) ?? GetDefaultConfig();
            }
            catch
            {
                return GetDefaultConfig();
            }
        }

        /// <summary>
        /// 将热键配置序列化并保存到 Preferences
        /// </summary>
        public void SaveConfig(HotKeyConfig config)
        {
            var json = JsonSerializer.Serialize(config);
            Preferences.Set(SettingsKey, json);
        }

        /// <summary>
        /// 重置为从 appsettings.json 中读取的默认值
        /// </summary>
        public void ResetToDefault()
        {
            var defaultConfig = GetDefaultConfig();
            SaveConfig(defaultConfig);
        }

        /// <summary>
        /// 获取默认热键配置
        /// </summary>
        private HotKeyConfig GetDefaultConfig()
        {
            return new HotKeyConfig
            {
                Modifiers = _appSettings.HotKey.DefaultModifiers,
                Key = _appSettings.HotKey.DefaultKey,
                IsEnabled = _appSettings.HotKey.DefaultIsEnabled
            };
        }
    }
}
