using Microsoft.Maui.Storage;
using System.Text.Json;
using TodoList.Maui.Models;

namespace TodoList.Maui.Services
{
    /// <summary>
    /// 热键设置服务接口
    /// </summary>
    public interface IHotKeySettingsService
    {
        /// <summary>
        /// 获取热键配置
        /// </summary>
        /// <returns>热键配置对象</returns>
        HotKeyConfig GetConfig();
        
        /// <summary>
        /// 保存热键配置
        /// </summary>
        /// <param name="config">热键配置对象</param>
        void SaveConfig(HotKeyConfig config);
        
        /// <summary>
        /// 重置为默认配置
        /// </summary>
        void ResetToDefault();
    }

    /// <summary>
    /// 热键设置服务实现类，使用 Preferences API 持久化配置
    /// </summary>
    public class HotKeySettingsService : IHotKeySettingsService
    {
        private const string SettingsKey = "HotKeyConfig";

        /// <summary>
        /// 获取热键配置
        /// </summary>
        /// <returns>热键配置对象，如果不存在则返回默认配置</returns>
        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>
        /// 保存热键配置
        /// </summary>
        /// <param name="config">热键配置对象</param>
        public void SaveConfig(HotKeyConfig config)
        {
            var json = JsonSerializer.Serialize(config);
            Preferences.Set(SettingsKey, json);
        }

        /// <summary>
        /// 重置为默认配置
        /// </summary>
        public void ResetToDefault()
        {
            var defaultConfig = GetDefaultConfig();
            SaveConfig(defaultConfig);
        }

        /// <summary>
        /// 获取默认热键配置
        /// </summary>
        /// <returns>默认热键配置对象</returns>
        private HotKeyConfig GetDefaultConfig()
        {
            return new HotKeyConfig
            {
                Modifiers = "Alt",
                Key = "X",
                IsEnabled = true
            };
        }
    }
}