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;

public final class SessionStore {
	private static final Gson GSON = new GsonBuilder().create();
	public String accessToken = "";
	public String refreshToken = "";
	public String name = "";
	public String userId = "";
	public String challengeId = "";
	public String reportSecret = "";
	public long seq;
	public long expiresAt;
	public String selectedUid = "";
	public String selectedName = "";

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

	public static SessionStore load() {
		Path path = file();
		if (!Files.isRegularFile(path)) return new SessionStore();
		try {
			SessionStore store = GSON.fromJson(Files.readString(path, StandardCharsets.UTF_8), SessionStore.class);
			return store == null ? new SessionStore() : store;
		} catch (Exception ignored) {
			return new SessionStore();
		}
	}

	public boolean signedIn() {
		return accessToken != null && accessToken.startsWith("sta_");
	}

	public boolean canSign() {
		return reportSecret != null && reportSecret.length() >= 16;
	}

	public synchronized long nextSeq() {
		seq += 1;
		save();
		return seq;
	}

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

	public void clear() {
		accessToken = "";
		refreshToken = "";
		name = "";
		userId = "";
		challengeId = "";
		reportSecret = "";
		seq = 0;
		expiresAt = 0;
		selectedUid = "";
		selectedName = "";
		try {
			Files.deleteIfExists(file());
		} catch (IOException ignored) {
		}
	}
}
