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

namespace AmiReel.Services;

public static class AppSettingsStore
{
    private static readonly JsonSerializerOptions JsonOptions = new() { WriteIndented = true };
    private static string DefaultOutputFolder => Environment.GetFolderPath(Environment.SpecialFolder.MyVideos);

    public static AppSettings Load()
    {
        string path = GetSettingsPath();
        if (!File.Exists(path))
            return AppSettings.Default(DefaultOutputFolder);

        try
        {
            string json = File.ReadAllText(path);
            return (JsonSerializer.Deserialize<AppSettings>(json, JsonOptions)
                ?? AppSettings.Default(DefaultOutputFolder))
                .Normalize(DefaultOutputFolder);
        }
        catch
        {
            return AppSettings.Default(DefaultOutputFolder);
        }
    }

    public static void Save(AppSettings settings)
    {
        string path = GetSettingsPath();
        Directory.CreateDirectory(Path.GetDirectoryName(path)!);
        string json = JsonSerializer.Serialize(settings, JsonOptions);
        File.WriteAllText(path, json);
    }

    private static string GetSettingsPath() => Path.Combine(
        Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
        "AmiReel", "settings.json");
}
