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

namespace NexusShell.Services;

public sealed class NexusMediaRecentService
{
    private static readonly JsonSerializerOptions JsonOptions = new() { WriteIndented = true };

    private readonly string _recentPath;
    private List<string> _recentPaths = [];

    public NexusMediaRecentService()
    {
        var root = Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
            "NinjaNexus",
            "media");
        Directory.CreateDirectory(root);
        _recentPath = Path.Combine(root, "recent.json");
        Load();
    }

    public string RecentPath => _recentPath;

    public event EventHandler? RecentChanged;

    public IReadOnlyList<string> GetRecentPaths() => _recentPaths.ToList();

    public void RecordPlayback(string fullPath)
    {
        if (string.IsNullOrWhiteSpace(fullPath))
        {
            return;
        }

        _recentPaths.RemoveAll(p => string.Equals(p, fullPath, StringComparison.OrdinalIgnoreCase));
        _recentPaths.Insert(0, fullPath);
        if (_recentPaths.Count > 100)
        {
            _recentPaths = _recentPaths.Take(100).ToList();
        }

        Save();
        RecentChanged?.Invoke(this, EventArgs.Empty);
    }

    private void Load()
    {
        if (!File.Exists(_recentPath))
        {
            return;
        }

        try
        {
            var json = File.ReadAllText(_recentPath);
            _recentPaths = JsonSerializer.Deserialize<List<string>>(json) ?? [];
        }
        catch
        {
            _recentPaths = [];
        }
    }

    private void Save()
    {
        var json = JsonSerializer.Serialize(_recentPaths, JsonOptions);
        File.WriteAllText(_recentPath, json);
    }
}
