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

namespace TodoList.Maui.Services
{
    public interface IHotKeySettingsService
    {
        HotKeyConfig GetConfig();
        void SaveConfig(HotKeyConfig config);
        void ResetToDefault();
    }

    public class HotKeySettingsService : IHotKeySettingsService
    {
        private const string SettingsKey = "HotKeyConfig";
        private readonly AppSettings _appSettings;

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

        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();
            }
        }

        public void SaveConfig(HotKeyConfig config)
        {
            var json = JsonSerializer.Serialize(config);
            Preferences.Set(SettingsKey, json);
        }

        public void ResetToDefault()
        {
            var defaultConfig = GetDefaultConfig();
            SaveConfig(defaultConfig);
        }

        private HotKeyConfig GetDefaultConfig()
        {
            return new HotKeyConfig
            {
                Modifiers = _appSettings.HotKey.DefaultModifiers,
                Key = _appSettings.HotKey.DefaultKey,
                IsEnabled = _appSettings.HotKey.DefaultIsEnabled
            };
        }
    }
}
