package moe.oko.opennaw.util;

import moe.oko.opennaw.OpenNAW;
import moe.oko.opennaw.model.City;
import moe.oko.opennaw.model.Nation;
import net.luckperms.api.model.group.Group;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;

import java.util.*;

public class NationHandler {

    private HashMap<String, Nation> nations = new HashMap<>();

    public void addNation(String name, Group group) {
        nations.put(name, new Nation(name, group));
    }

    public void removeNation(String name) {
        nations.remove(name);
    }

    public Group getNationGroup(String name) {
        return nations.get(name).getGroup();
    }

    public Nation getNationByName(String name) { return nations.get(name); }

    public boolean isPlayerInNation(Player player, Nation nation) {
        return nation.getPlayerMap().containsKey(player.getUniqueId());
    }

    public Nation getNationByPlayer(UUID uuid) {
        for(var nation : nations.values()) {
            if(nation.getPlayerMap().containsKey(uuid)) {
                return nation;
            }
        }
        return null;
    }

    public Nation fetchNationViaName(String name) {
        if(name.equals(Nation.UNCLAIMED.getName())) { return Nation.UNCLAIMED; }
        for(Nation cty : nations.values()) {
            if(cty.getName().equalsIgnoreCase(name)) {
                return cty;
            }
        }
        return null;
    }

    //Database loading players.
    public void insertPlayerIntoNation(UUID uuid, String nation) {
        for(var result : nations.values()) {
            if (result.getName().equals(nation)) {
                result.getPlayerMap().put(uuid, Bukkit.getOfflinePlayer(uuid));
            }
        }
    }

    public void loadNationList(List<Nation> nations) {
        for(Nation nation : nations) {
            this.nations.put(nation.getName(), nation);
        }
    }

    public List<String> getNationStringList() {
        List<String> nationList = new ArrayList<String>();
        for (Nation nation : nations.values()) {
            nationList.add(nation.getName());
        }
        return nationList;
    }

    public Collection<Nation> getNationList() {
        return nations.values();
    }

    public void saveNations() {
        OpenNAW.getInstance().getDatabase().saveNations(nations.values());
    }
}
