using Mlaumcherb.Client.Avalonia.зримое;
using Mlaumcherb.Client.Avalonia.классы;
using Mlaumcherb.Client.Avalonia.сеть.Update;
using Mlaumcherb.Client.Avalonia.холопы;

namespace Mlaumcherb.Client.Avalonia;

public record Config
{
    [JsonRequired] public string config_version { get; set; } = "1.0.0";
    public bool debug { get; set; } = 
#if DEBUG
        true;
#else
        false;
#endif
    public string player_name { get; set; } = "";
    public int max_memory { get; set; } = 4096;
    public string minecraft_dir { get; set; } = ".";
    public bool download_java { get; set; } = true;
    public bool redirect_game_output { get; set; } = false;
    public string? last_launched_version { get; set; }
    public int max_parallel_downloads { get; set; } = 16;
    public GameVersionCatalogProps[] version_catalogs { get; set; } =
    [
        new() { name = "Тимериховое", url = "https://timerix.ddns.net/minecraft/catalog.json" },
        new() { name = "Mojang", url = "https://piston-meta.mojang.com/mc/game/version_manifest_v2.json" },
    ];
    
    public UpdateHelper.GiteaConfig gitea { get; set; } = new()
    {
        serverUrl = "https://timerix.ddns.net/git/",
        user = "Timerix",
        repo = "mlaumcherb",
    };

    
    [JsonIgnore] private static IOPath _filePath = "млаумчерб.json";
    
    public static Config LoadFromFile()
    {
        LauncherApp.Logger.LogDebug(nameof(Config), $"loading config from file '{_filePath}'");
        if(!File.Exists(_filePath))
        {
            LauncherApp.Logger.LogDebug(nameof(Config), "file doesn't exist");
            return new Config();
        }

        string text = File.ReadAllText(_filePath);
        string errorMessage = "config is empty";
        Config? config = null;
        try
        {
            config = JsonConvert.DeserializeObject<Config>(text);
        }
        catch (Exception ex)
        {
            errorMessage = ex.Message;
        }
        if (config == null)
        {
            IOPath _brokenPath = _filePath + ".broken";
            File.Move(_filePath, _brokenPath, true);
            ErrorHelper.ShowMessageBox(nameof(Config), 
                $"Can't reed config file '{_filePath}'.\n" +
                $"New config file has been created. Old is renamed to '{_brokenPath}'.\n\n" +
                $"Config parser error: {errorMessage}");
            config = new Config();
            config.SaveToFile();
        }

        LauncherApp.Logger.LogDebug(nameof(Config), $"config has been loaded: {config}");
        return config;
    }

    public void SaveToFile()
    {
        LauncherApp.Logger.LogDebug(nameof(Config), $"saving config to file '{_filePath}'");
        var text = JsonConvert.SerializeObject(this, Formatting.Indented);
        File.WriteAllText(_filePath, text);
        LauncherApp.Logger.LogDebug(nameof(Config), $"config has been saved: {text}");
    }
}