using System;
using System.IO;
using Tommy;

namespace PlombirLauncher;

public class ConfigManager
{
    public static void BuildDefault()
    {
        TomlTable toml = new TomlTable
        {
            ["title"] = "Launcher tweaks file!",

            ["runtime-path"] = new TomlString
            {
                Value = "./runtime",
                Comment = "Path to folder that will hold all minecraft versions"
            },

            ["last-version-launched"] = new TomlString
            {
                Value = "1.20.1",
                Comment = "Saving last launched version to use it after launch"
            },

            ["nickname"] = "slugcat"
        };

        using(StreamWriter writer = File.CreateText("tweaks.toml"))
        {
            toml.WriteTo(writer);
            // Remember to flush the data if needed!
            writer.Flush();
        }
    }

    public static dynamic? ReadConfig(string key)
    {
        if (!File.Exists("tweaks.toml"))
        {
            BuildDefault();
        }
        using(StreamReader reader = File.OpenText("tweaks.toml"))
        {
            TomlTable table = TOML.Parse(reader);

            return table[key];
        }
    }

    public static void WriteInConfig(string key, dynamic value)
    {
        if (!File.Exists("tweaks.toml"))
        {
            BuildDefault();
        }

        TomlTable table;

        using(StreamReader reader = File.OpenText("tweaks.toml"))
        {
            table = TOML.Parse(reader);

            table[key] = value;
        }

        using(StreamWriter writer = File.CreateText("tweaks.toml"))
        {
            table.WriteTo(writer);
            // Remember to flush the data if needed!
            writer.Flush();
        }
    }
}