package com.zivilon.cinder_loe.character;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.*;
import java.nio.file.*;
import java.lang.reflect.Type;
import java.util.*;

public class CharacterRoleAPI {

    private static final Path FILE_PATH = Paths.get("character_roles.json");
    private static Map<String, UUID> characterRoles = new HashMap<>();

    public static void loadRolesFromFile() {
        if (!Files.exists(FILE_PATH)) {
            try {
                Files.createFile(FILE_PATH);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }

        try (Reader reader = Files.newBufferedReader(FILE_PATH)) {
            Gson gson = new Gson();
            Type type = new TypeToken<Map<String, UUID>>() {}.getType();
            characterRoles = gson.fromJson(reader, type);
            if (characterRoles == null) {
                characterRoles = new HashMap<>();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void saveRolesToFile() {
        Gson gson = new Gson();
        try (Writer writer = Files.newBufferedWriter(FILE_PATH)) {
            gson.toJson(characterRoles, writer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static UUID getCharacterRoleUUID(String roleName) {
        return characterRoles.get(roleName);
    }

    public static void setCharacterRoleUUID(String roleName, UUID playerUUID) {
        characterRoles.put(roleName, playerUUID);
        saveRolesToFile();
    }

    public static void removeCharacterRole(String roleName) {
        if (characterRoles.containsKey(roleName)) {
            characterRoles.remove(roleName);
            saveRolesToFile();
        }
    }
}
