using System;
using System.IO;
using System.Text.Json;

namespace TeamsISO.App.WinUI.Services;

/// <summary>
/// Persistent UI-side toggles shared between hosts via JSON at
/// %LOCALAPPDATA%\TeamsISO\ui-prefs.json. The WPF host's copy at
/// src/TeamsISO.App/Services/UIPreferences.cs reads/writes the same
/// file with the same record shape — new fields added in one host's
/// copy degrade gracefully in the other (JSON deserializer ignores
/// unknown fields, missing fields fall back to defaults).
///
/// The WinUI copy adds the Theme field which the WPF host doesn't
/// know about yet; when the WPF host's UIPreferences gets the same
/// field, both hosts will share the operator's theme choice across
/// host swaps.
/// </summary>
public static class UIPreferences
{
    private static readonly object _gate = new();

    private static string PrefsPath =>
        Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
            "TeamsISO", "ui-prefs.json");

    public enum SortMode { JoinOrder, Alphabetical, OnlineFirst, LoudestFirst }

    /// <summary>The on-disk shape. New fields added here become opt-in for older files via default values.</summary>
    public sealed record Prefs(
        bool HideLocalSelf = true,
        bool AutoDisableOnDeparture = false,
        SortMode ParticipantSort = SortMode.JoinOrder,
        bool MinimizeToTray = false,
        bool ControlSurfaceLanReachable = false,
        bool LaunchTeamsOnStartup = false,
        bool AutoHideTeamsWindows = false,
        bool AutoRecordOnCall = false,
        bool EmbedTeamsWindow = false,
        // Theme preference: "System" (follow OS app-mode), "Dark", or
        // "Light". WinUI host owns the value for now; WPF host gets the
        // same field in its UIPreferences when its theme system lands.
        string Theme = "System");

    public static Prefs Load()
    {
        try
        {
            if (!File.Exists(PrefsPath)) return new Prefs();
            var json = File.ReadAllText(PrefsPath);
            return JsonSerializer.Deserialize<Prefs>(json) ?? new Prefs();
        }
        catch
        {
            return new Prefs();
        }
    }

    public static void Save(Prefs prefs)
    {
        try
        {
            lock (_gate)
            {
                var dir = Path.GetDirectoryName(PrefsPath);
                if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
                var json = JsonSerializer.Serialize(prefs, new JsonSerializerOptions { WriteIndented = true });
                File.WriteAllText(PrefsPath, json);
            }
        }
        catch
        {
            // Disk full / permission denied — in-memory state still holds for this session.
        }
    }

    /// <summary>Update just the Theme field without touching other prefs.</summary>
    public static void SetTheme(string theme)
    {
        var current = Load();
        Save(current with { Theme = theme });
    }
}
