package moe.oko.opennaw.util;

import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import moe.oko.opennaw.OpenNAW;
import moe.oko.opennaw.model.Nation;
import org.bukkit.Location;
import org.bukkit.entity.Player;

public class WorldGuardHelper {

    /*
    Used to set the owner when a city is captured namely.
     */
    public static void setRegionOwner(ProtectedRegion region, Nation nation) {
        region.getMembers().clear(); //Clear prior owner.
        region.getMembers().addGroup(nation.getGroup().getName());
    }

    /*
    Used to determine whether a player can open a gate, or BETRAY epicly.
     */
    public static boolean isPlayerPermitted(ProtectedRegion region, Player player) {
        var nation = OpenNAW.getInstance().getNationHandler().getNationByPlayer(player.getUniqueId());
        if(region.getMembers().getGroups().contains(nation.getGroup().getName())) {
            return true;
        } else {
            return false;
        }
    }

    /*
    This will ONLY return city regions. DO NOT LET CITY REGIONS OVERLAP, THIS CAN CAUSE A LOT OF BUGS.
     */
    public static ProtectedRegion fetchCityRegionViaLoc(Location location) {
        var regionsOnLoc =  WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().getApplicableRegions(BukkitAdapter.adapt(location)).getRegions();
        var cityStrs = OpenNAW.getInstance().getCityHandler().getCityList();
        for(var protreg : regionsOnLoc) {
            if(cityStrs.contains(protreg.getId())) {
                return protreg;
            }
        }
        return null;
    }
}
