package wtf.sten.vault;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import net.fabricmc.loader.api.FabricLoader;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.SecureRandom;
import java.util.Base64;

public final class VaultConfig {
	private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
	private static VaultConfig instance;

	public boolean titleButton = true;
	public boolean openOnLaunch = false;
	public boolean remoteControl = true;
	public boolean autoScreenshot = true;
	public int autoScreenshotSeconds = 15;
	public boolean showSkins = true;
	public String sort = "newest";
	public String rankFilter = "";
	public String capeFilter = "";
	public double minValue = 0;
	public double minDonut = 0;
	public String proxy = "";
	public String deviceId = "";

	public static Path file() {
		return FabricLoader.getInstance().getConfigDir().resolve("sten-vault.json");
	}

	public static VaultConfig get() {
		if (instance == null) instance = load();
		return instance;
	}

	public static VaultConfig load() {
		Path path = file();
		VaultConfig cfg = new VaultConfig();
		if (Files.isRegularFile(path)) {
			try {
				cfg = GSON.fromJson(Files.readString(path, StandardCharsets.UTF_8), VaultConfig.class);
				if (cfg == null) cfg = new VaultConfig();
			} catch (Exception ignored) {
				cfg = new VaultConfig();
			}
		}
		if (cfg.autoScreenshotSeconds < 10) cfg.autoScreenshotSeconds = 15;
		if (cfg.autoScreenshotSeconds > 60) cfg.autoScreenshotSeconds = 60;
		if (cfg.sort == null || cfg.sort.isBlank()) cfg.sort = "newest";
		if (cfg.rankFilter == null) cfg.rankFilter = "";
		if (cfg.capeFilter == null) cfg.capeFilter = "";
		if (cfg.proxy == null) cfg.proxy = "";
		if (cfg.minValue < 0) cfg.minValue = 0;
		if (cfg.minDonut < 0) cfg.minDonut = 0;
		if (cfg.deviceId == null || cfg.deviceId.length() < 16) {
			byte[] raw = new byte[24];
			new SecureRandom().nextBytes(raw);
			cfg.deviceId = Base64.getUrlEncoder().withoutPadding().encodeToString(raw);
			cfg.save();
		}
		instance = cfg;
		return cfg;
	}

	public void save() {
		try {
			Files.createDirectories(file().getParent());
			Files.writeString(file(), GSON.toJson(this), StandardCharsets.UTF_8);
		} catch (IOException ignored) {
		}
	}
}
