package sh.grimmer.bettershulkers;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.loader.api.FabricLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sh.grimmer.bettershulkers.config.BetterShulkersConfig;

import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Path;

public class BetterShulkers implements ModInitializer {

    public static final String MOD_ID = "better_shulkers";
    public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);
    public static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();

    public static BetterShulkersConfig CONFIG;

    @Override
    public void onInitialize() {
        CONFIG = loadConfig();
    }

    private static BetterShulkersConfig loadConfig() {
        Path configPath = getConfigPath();
        if (Files.exists(configPath)) {
            try (Reader reader = Files.newBufferedReader(configPath)) {
                BetterShulkersConfig loaded = GSON.fromJson(reader, BetterShulkersConfig.class);
                if (loaded != null) {
                    loaded.save();
                    return loaded;
                }
            } catch (Exception e) {
                LOGGER.error("Failed to load config, using defaults", e);
            }
        }
        BetterShulkersConfig config = new BetterShulkersConfig();
        config.save();
        return config;
    }

    public static Path getConfigPath() {
        return FabricLoader.getInstance().getConfigDir().resolve(MOD_ID + ".json");
    }

    public static void saveConfig() {
        if (CONFIG != null) {
            CONFIG.save();
        }
    }
}
