package tc.oc.pgm.modules;

import net.md_5.bungee.api.chat.TranslatableComponent;
import org.bukkit.Location;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.util.Vector;

import tc.oc.commons.bukkit.util.BlockUtils;
import tc.oc.pgm.events.ListenerScope;
import tc.oc.pgm.match.Match;
import tc.oc.pgm.match.MatchModule;
import tc.oc.pgm.match.MatchPlayer;
import tc.oc.pgm.events.BlockTransformEvent;
import tc.oc.commons.bukkit.event.CoarsePlayerMoveEvent;
import tc.oc.pgm.match.MatchScope;
import tc.oc.pgm.regions.Region;
import tc.oc.pgm.utils.MatchPlayers;


@ListenerScope(MatchScope.RUNNING)
public class PlayableRegionMatchModule extends MatchModule implements Listener {
    protected final Region playableRegion;

    public PlayableRegionMatchModule(Match match, Region playableRegion){
        super(match);
        this.playableRegion = playableRegion;
    }

    @EventHandler(ignoreCancelled = true)
    public void onBlockTransformEvent(final BlockTransformEvent event) {
        Location center = BlockUtils.center(event.getNewState());
        if(!this.playableRegion.contains(center.toVector())) {
            event.setCancelled(true, new TranslatableComponent("match.playableArea.blockInteractWarning"));
        }
    }

    @EventHandler(ignoreCancelled = true)
    public void onCoarsePlayerMoveEvent(final CoarsePlayerMoveEvent event) {
        MatchPlayer player = this.match.getPlayer(event.getPlayer());

        if(MatchPlayers.canInteract(player)) {
            Vector from = BlockUtils.center(event.getFrom()).toVector();
            Vector to = BlockUtils.center(event.getTo()).toVector();
            if(this.playableRegion.contains(from) && !this.playableRegion.contains(to)) {
                event.setCancelled(true, new TranslatableComponent("match.playableArea.leaveAreaWarning"));
            }
        }
    }
}
