using System.IO;
using System.Text.Json;
using NexusShell.Models;

namespace NexusShell.Services;

public sealed class UserSettingsService
{
    private readonly string _folder;
    private readonly string _settingsPath;
    private readonly string _wallpapersFolder;

    public UserSettingsService()
    {
        _folder = Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
            "NinjaNexus");
        _settingsPath = Path.Combine(_folder, "settings.json");
        _wallpapersFolder = Path.Combine(_folder, "Wallpapers");
        Directory.CreateDirectory(_folder);
        Directory.CreateDirectory(_wallpapersFolder);
        Current = Load();
    }

    public NexusUserSettings Current { get; private set; }

    public event EventHandler? SettingsChanged;

    public IReadOnlyList<string> BundledWallpapers { get; } =
    [
        NexusAssets.DesktopWallpaper,
    ];

    public void Save(NexusUserSettings settings)
    {
        Current = settings;
        var json = JsonSerializer.Serialize(settings, JsonOptions);
        File.WriteAllText(_settingsPath, json);
        SettingsChanged?.Invoke(this, EventArgs.Empty);
    }

    public NexusUserSettings Load()
    {
        if (!File.Exists(_settingsPath))
        {
            Current = new NexusUserSettings();
            return Current;
        }

        try
        {
            var json = File.ReadAllText(_settingsPath);
            Current = JsonSerializer.Deserialize<NexusUserSettings>(json, JsonOptions) ?? new NexusUserSettings();
        }
        catch
        {
            Current = new NexusUserSettings();
        }

        if (Current.SettingsVersion < 1)
        {
            Current.SpanAllMonitors = false;
            Current.SettingsVersion = 1;
            Save(Current);
        }

        if (Current.SettingsVersion < 2)
        {
            if (string.IsNullOrWhiteSpace(Current.AccentColor))
            {
                Current.AccentColor = "auto";
            }

            if (string.IsNullOrWhiteSpace(Current.AnimationIntensity))
            {
                Current.AnimationIntensity = "normal";
            }

            Current.SettingsVersion = 2;
            Save(Current);
        }

        return Current;
    }

    public string ResolveWallpaperUri()
    {
        var path = Current.WallpaperPath?.Trim();
        if (!string.IsNullOrWhiteSpace(path) && File.Exists(path))
        {
            return new Uri(path, UriKind.Absolute).AbsoluteUri;
        }

        return NexusAssets.DesktopWallpaper;
    }

    public string ImportCustomWallpaper(string sourcePath)
    {
        if (!File.Exists(sourcePath))
        {
            throw new FileNotFoundException("Baggrundsfilen findes ikke.", sourcePath);
        }

        var extension = Path.GetExtension(sourcePath);
        if (string.IsNullOrWhiteSpace(extension))
        {
            extension = ".png";
        }

        var fileName = $"wallpaper-{DateTime.UtcNow:yyyyMMddHHmmss}{extension}";
        var destination = Path.Combine(_wallpapersFolder, fileName);
        File.Copy(sourcePath, destination, overwrite: true);
        Current.WallpaperPath = destination;
        Save(Current);
        return destination;
    }

    public void ResetWallpaperToDefault()
    {
        Current.WallpaperPath = string.Empty;
        Save(Current);
    }

    private static readonly JsonSerializerOptions JsonOptions = new()
    {
        PropertyNameCaseInsensitive = true,
        WriteIndented = true,
    };
}
