using Avalonia.Controls.Templates;
using ReactiveUI;
using Serilog.Events;
using System;
using System.IO;
using System.Linq;
using System.Text.Json;
using VeloeMinecraftLauncher.Utils.Logger;

namespace VeloeMinecraftLauncher.Utils;

internal static class SettingsService
{
    //public static readonly string JavaPath = "C:\\Program Files\\Microsoft\\jdk-11.0.12.7-hotspot\\bin\\java.exe";
    public static SettingsSerializable Instance { get; set; }

    public static Serilog.ILogger? logger;
    public static CaptureFilePathHook? logFilePath;
    public static Serilog.ILogger? avaloniaLogger;

    public static void LoadSettings()
    {
        if (!File.Exists($"settings.json"))
        {
            var file = File.Create($"settings.json");
            file.Close();
            file.Dispose();
        }

        var settings = File.ReadAllText($"settings.json");

        if (settings != String.Empty)
        {
            try
            {
                Instance = JsonSerializer.Deserialize<SettingsSerializable>(settings, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }) ?? new SettingsSerializable();
            }
            catch (JsonException ex)
            {
                logger?.Error(ex.Message);
            }
        }
        else
        {
            Instance = new SettingsSerializable();
            logger?.Warning("Empty settings.json");
        }
    }

    public static void SaveSettings()
    {
        if(string.IsNullOrWhiteSpace(Instance.MinecraftForlderPath))
            Instance.MinecraftForlderPath = Directory.GetCurrentDirectory();

        if(Instance.MinecraftForlderPath.Last() is not ('/' or '\\'))
            Instance.MinecraftForlderPath += "/";

        if (!Directory.Exists(Instance.MinecraftForlderPath))
            Directory.CreateDirectory(Instance.MinecraftForlderPath);

        var settings = JsonSerializer.Serialize(Instance);

        File.WriteAllText($"settings.json", settings);
    }
}