package de.steamwar.bausystem.features.region;

import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.region.Region;
import de.steamwar.bausystem.region.flags.Flag;
import de.steamwar.bausystem.region.flags.flagvalues.ProtectMode;
import de.steamwar.bausystem.utils.ScoreboardElement;
import de.steamwar.linkage.Linked;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockExplodeEvent;
import org.bukkit.event.entity.EntityExplodeEvent;

import java.util.List;

@Linked
public class ProtectListener implements Listener, ScoreboardElement {

    private void explode(List<Block> blockList, Location location) {
        Region region = Region.getRegion(location);
        if (region.getFloorLevel() == 0) {
            return;
        }
        if (region.getPlain(Flag.PROTECT, ProtectMode.class) == ProtectMode.INACTIVE) {
            return;
        }
        blockList.removeIf(block -> block.getY() < region.getFloorLevel());
    }

    @EventHandler
    public void onBlockExplode(BlockExplodeEvent event) {
        explode(event.blockList(), event.getBlock().getLocation());
    }

    @EventHandler
    public void onExplode(EntityExplodeEvent event) {
        explode(event.blockList(), event.getLocation());
    }

    @Override
    public ScoreboardGroup getGroup() {
        return ScoreboardGroup.REGION;
    }

    @Override
    public int order() {
        return 2;
    }

    @Override
    public String get(Region region, Player p) {
        if (region.getFloorLevel() == 0) return null;
        if (region.get(Flag.PROTECT) != Flag.PROTECT.getDefaultValue()) return null;
        return "§e" + BauSystem.MESSAGE.parse(Flag.PROTECT.getChatValue(), p) + "§8: " + BauSystem.MESSAGE.parse(region.get(Flag.PROTECT).getChatValue(), p);
    }
}
