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

namespace ModpackLauncher.Models;

public sealed class LauncherSettings
{
    [JsonPropertyName("memoryMB")]
    public int? MemoryMB { get; set; }

    [JsonPropertyName("installDirOverride")]
    public string? InstallDirOverride { get; set; }

    /// <summary>
    /// Settings live next to the launcher exe ("sidecar"), so each copy of
    /// the launcher has its own independent state. Drop the launcher in a
    /// new folder on a different machine, or alongside the existing one in
    /// a separate directory, and they remember their own install paths,
    /// memory choices, etc. Matches the portable-app convention.
    /// </summary>
    private static string FilePath
        => Path.Combine(AppContext.BaseDirectory, "launcher-settings.json");

    public static LauncherSettings Load()
    {
        try
        {
            if (!File.Exists(FilePath)) return new LauncherSettings();
            return JsonSerializer.Deserialize<LauncherSettings>(File.ReadAllText(FilePath))
                   ?? new LauncherSettings();
        }
        catch
        {
            return new LauncherSettings();
        }
    }

    public void Save()
    {
        try
        {
            File.WriteAllText(
                FilePath,
                JsonSerializer.Serialize(this, new JsonSerializerOptions { WriteIndented = true })
            );
        }
        catch
        {
            // best-effort
        }
    }
}
