using Hua.Todo.Avalonia.Models;
using System;
using System.IO;
using System.Text.Json;

namespace Hua.Todo.Avalonia.Services;

/// <summary>
/// 热键设置服务接口。
/// 负责读取/保存用户可配置的全局热键，并提供从默认值重置的能力。
/// </summary>
public interface IHotKeySettingsService
{
    /// <summary>
    /// 获取当前热键配置（若尚未持久化则返回默认配置）。
    /// </summary>
    HotKeyConfig GetConfig();

    /// <summary>
    /// 保存热键配置。
    /// </summary>
    /// <param name="config">要保存的热键配置。</param>
    void SaveConfig(HotKeyConfig config);

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

/// <summary>
/// 热键设置服务实现。
/// Avalonia 侧使用本地 JSON 文件持久化配置，以保证桌面端与多平台运行时一致性。
/// </summary>
public sealed class HotKeySettingsService : IHotKeySettingsService
{
    private const string SettingsFileName = "hotkey.json";
    private readonly AppSettings _appSettings;
    private HotKeyConfig? _cached;

    /// <summary>
    /// 创建 <see cref="HotKeySettingsService"/>。
    /// </summary>
    /// <param name="appSettings">应用配置（用于提供默认热键）。</param>
    public HotKeySettingsService(AppSettings appSettings)
    {
        _appSettings = appSettings;
    }

    /// <inheritdoc />
    public HotKeyConfig GetConfig()
    {
        if (_cached != null)
        {
            return _cached;
        }

        var path = GetSettingsPath();
        if (!File.Exists(path))
        {
            _cached = GetDefaultConfig();
            return _cached;
        }

        try
        {
            var json = File.ReadAllText(path);
            _cached = JsonSerializer.Deserialize<HotKeyConfig>(json) ?? GetDefaultConfig();
            return _cached;
        }
        catch
        {
            _cached = GetDefaultConfig();
            return _cached;
        }
    }

    /// <inheritdoc />
    public void SaveConfig(HotKeyConfig config)
    {
        var path = GetSettingsPath();
        EnsureSettingsDirectory(path);

        var json = JsonSerializer.Serialize(config);
        File.WriteAllText(path, json);

        _cached ??= config;
    }

    /// <inheritdoc />
    public void ResetToDefault()
    {
        var defaultConfig = GetDefaultConfig();
        var current = GetConfig();

        current.Modifiers = defaultConfig.Modifiers;
        current.Key = defaultConfig.Key;
        current.IsEnabled = defaultConfig.IsEnabled;

        SaveConfig(current);
    }

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

    private static string GetSettingsPath()
    {
        var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
        var dir = Path.Combine(localAppData, "Hua.Todo");
        return Path.Combine(dir, SettingsFileName);
    }

    private static void EnsureSettingsDirectory(string settingsPath)
    {
        var dir = Path.GetDirectoryName(settingsPath);
        if (string.IsNullOrWhiteSpace(dir))
        {
            return;
        }

        Directory.CreateDirectory(dir);
    }
}
