package moe.oko.opennaw.listener;

import moe.oko.opennaw.OpenNAW;
import moe.oko.opennaw.util.TNTHandler;
import moe.oko.opennaw.util.WorldGuardHelper;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.player.PlayerInteractAtEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;

public class TNTListener implements Listener {

    @EventHandler
    public void onBlockPlace(BlockPlaceEvent event) {
        //Explosives Prevention
        if(event.getBlock().getType().equals(Material.TNT)) {
            if(event.getBlock().getLocation().subtract(0, 1, 0).getBlock().getType().equals(Material.SOUL_SAND)) {
                if(WorldGuardHelper.fetchCityRegionViaLoc(event.getBlock().getLocation()) != null) {
                    OpenNAW.getInstance().getTntHandler().startExplosive(event.getBlock(), event.getPlayer());
                } else {
                    event.getPlayer().sendMessage(ChatColor.RED + "" + ChatColor.ITALIC
                            + "It would be a waste to blow this up here... It's about sending a message isn't it?");
                    event.setCancelled(true);
                }
            } else {
                event.getPlayer().sendMessage(ChatColor.RED + "" + ChatColor.ITALIC
                        + "The ground here isn't sticky enough to hold together the badly constructed explosive. Maybe soul sand would work?");
                event.setCancelled(true);
            }
        }
    }

    @EventHandler
    public void onEntityExplosion(EntityExplodeEvent event) {
        if(event.getEntity().getType().equals(EntityType.PRIMED_TNT)) {
            OpenNAW.getInstance().getTntHandler().detonate(event);
        }
    }

    @EventHandler
    public void onPlayerInteract(PlayerInteractAtEntityEvent event) {
        if(event.getRightClicked().getType().equals(EntityType.PRIMED_TNT)) {
            if(WorldGuardHelper.fetchCityRegionViaLoc(event.getRightClicked().getLocation()) != null) {
                var rg = WorldGuardHelper.fetchCityRegionViaLoc(event.getRightClicked().getLocation());
                if(WorldGuardHelper.isPlayerPermitted(rg, event.getPlayer())) {
                    OpenNAW.getInstance().getTntHandler().defuse((TNTPrimed) event.getRightClicked());
                }
            }
        }
    }
}
