/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package pw.yumc.Residence.listeners;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Arrow;
import org.bukkit.entity.Creeper;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.Wolf;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.EntityChangeBlockEvent;
import org.bukkit.event.entity.EntityCombustEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.EntityInteractEvent;
import org.bukkit.event.entity.ExplosionPrimeEvent;
import org.bukkit.event.entity.PotionSplashEvent;
import org.bukkit.event.hanging.HangingBreakByEntityEvent;
import org.bukkit.event.hanging.HangingBreakEvent;
import org.bukkit.event.hanging.HangingPlaceEvent;

import com.bekvon.bukkit.residence.protection.ClaimedResidence;
import com.bekvon.bukkit.residence.protection.FlagPermissions;

import pw.yumc.Residence.ResidenceMain;
import pw.yumc.Residence.manager.EntityManager;

/**
 *
 * @author Administrator
 */
public class ResidenceEntityListener implements Listener {
    EntityManager entitymanager;
    ResidenceMain plugin;

    public ResidenceEntityListener(final ResidenceMain plugin) {
        this.plugin = plugin;
        this.entitymanager = plugin.getEntityManager();
    }

    @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
    public void onCreatureSpawn(final CreatureSpawnEvent event) {
        final FlagPermissions perms = plugin.getPermsByLoc(event.getLocation());
        final Entity ent = event.getEntity();
        if (entitymanager.isAnimal(ent)) {
            if (!perms.has("animals", true)) {
                event.setCancelled(true);
            }
        } else if (!perms.has("monsters", true) && entitymanager.isMonster(ent)) {
            event.setCancelled(true);
        }
    }

    @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
    public void onEndermanChangeBlock(final EntityChangeBlockEvent event) {
        if (event.getEntityType() != EntityType.ENDERMAN && event.getEntityType() != EntityType.WITHER) {
            return;
        }
        final FlagPermissions perms = plugin.getPermsByLoc(event.getBlock().getLocation());
        final FlagPermissions world = plugin.getWorldFlags().getPerms(event.getBlock().getWorld().getName());
        if (event.getEntityType() == EntityType.WITHER) {
            if (!perms.has("wither", perms.has("explode", world.has("wither", world.has("explode", true))))) {
                event.setCancelled(true);
            }
        } else if (!perms.has("build", true)) {
            event.setCancelled(true);
        }
    }

    @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
    public void onEntityCombust(final EntityCombustEvent event) {
        final FlagPermissions perms = plugin.getPermsByLoc(event.getEntity().getLocation());
        if (!perms.has("burn", true)) {
            event.setCancelled(true);
        }
    }

    @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
    public void onEntityDamage(final EntityDamageEvent event) {
        Entity ent = event.getEntity();
        if (ent.hasMetadata("NPC")) {
            return;
        }
        final boolean tamedWolf = ent instanceof Wolf ? ((Wolf) ent).isTamed() : false;
        final ClaimedResidence area = plugin.getResidenceManager().getByLoc(ent.getLocation());
        /* Living Entities */
        if (event instanceof EntityDamageByEntityEvent) {
            final EntityDamageByEntityEvent attackevent = (EntityDamageByEntityEvent) event;
            final Entity damager = attackevent.getDamager();
            ClaimedResidence srcarea = null;
            if (damager != null) {
                srcarea = plugin.getResidenceManager().getByLoc(damager.getLocation());
            }
            boolean srcpvp = true;
            if (srcarea != null) {
                srcpvp = srcarea.getPermissions().has("pvp", true);
            }
            ent = attackevent.getEntity();
            // 屏蔽1.6.x不存在getShooter方法导致的报错...
            boolean isPlayerArrow = false;
            try {
                isPlayerArrow = damager instanceof Arrow && (((Arrow) damager).getShooter() instanceof Player);
            } catch (final Exception e) {
            }
            if ((ent instanceof Player || tamedWolf) && (damager instanceof Player || isPlayerArrow)) {
                Player attacker = null;
                if (damager instanceof Player) {
                    attacker = (Player) damager;
                } else if (damager instanceof Arrow) {
                    attacker = (Player) ((Arrow) damager).getShooter();
                }
                if (!srcpvp) {
                    if (attacker != null) {
                        attacker.sendMessage(ChatColor.RED + plugin.getLanguage().getPhrase("NoPVPZone"));
                    }
                    event.setCancelled(true);
                    return;
                }
                /* Check for Player vs Player */
                if (area == null) {
                    /* World PvP */
                    if (damager != null) {
                        if (!plugin.getWorldFlags().getPerms(damager.getWorld().getName()).has("pvp", true)) {
                            if (attacker != null) {
                                attacker.sendMessage(ChatColor.RED + plugin.getLanguage().getPhrase("WorldPVPDisabled"));
                            }
                            event.setCancelled(true);
                        }
                    }
                } else /* Normal PvP */
                if (!area.getPermissions().has("pvp", true)) {
                    if (attacker != null) {
                        attacker.sendMessage(ChatColor.RED + plugin.getLanguage().getPhrase("NoPVPZone"));
                    }
                    event.setCancelled(true);
                }
                return;
            } else if ((ent instanceof Player || tamedWolf) && (damager instanceof Creeper)) {
                if (area == null) {
                    if (!plugin.getWorldFlags().getPerms(damager.getWorld().getName()).has("creeper", true)) {
                        event.setCancelled(true);
                    }
                } else if (!area.getPermissions().has("creeper", true)) {
                    event.setCancelled(true);
                }
            }
        }
        if (area == null) {
            if (!plugin.getWorldFlags().getPerms(ent.getWorld().getName()).has("damage", true) && (ent instanceof Player || tamedWolf)) {
                event.setCancelled(true);
            }
        } else if (!area.getPermissions().has("damage", true) && (ent instanceof Player || tamedWolf)) {
            event.setCancelled(true);
        }
        if (event.isCancelled()) {
            /* Put out a fire on a player */
            if ((ent instanceof Player || tamedWolf) && (event.getCause() == EntityDamageEvent.DamageCause.FIRE || event.getCause() == EntityDamageEvent.DamageCause.FIRE_TICK)) {
                ent.setFireTicks(0);
            }
        }
    }

    @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
    public void onEntityDamageByEntityEvent(final EntityDamageByEntityEvent event) {
        if (event.getEntityType() == EntityType.ITEM_FRAME || (plugin.isGt1_8() && event.getEntityType() == EntityType.ARMOR_STAND)) {
            final Entity dmgr = event.getDamager();
            Player player;
            if (dmgr instanceof Player) {
                player = (Player) event.getDamager();
            } else if (dmgr instanceof Projectile && ((Projectile) dmgr).getShooter() instanceof Player) {
                player = (Player) ((Projectile) dmgr).getShooter();
            } else {
                return;
            }

            if (plugin.isResAdminOn(player)) {
                return;
            }

            // Note: Location of entity, not player; otherwise player could stand outside of res and still damage
            final Location loc = event.getEntity().getLocation();
            final ClaimedResidence res = plugin.getResidenceManager().getByLoc(loc);
            if (res != null) {
                if (!res.getPermissions().has("container", false)) {
                    if (entitymanager.isMonster(dmgr)) {
                        event.setCancelled(true);
                        return;
                    }
                }

                if (!res.getPermissions().playerHas(player.getName(), "container", false)) {
                    event.setCancelled(true);
                    player.sendMessage(ChatColor.RED + plugin.getLanguage().getPhrase("FlagDeny", "container"));
                }
            }
        }
    }

    @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
    public void onEntityExplode(final EntityExplodeEvent event) {
        if (event.isCancelled() || event.getEntity() == null) {
            return;
        }
        Boolean cancel = false;
        final EntityType entity = event.getEntityType();
        final FlagPermissions perms = plugin.getPermsByLoc(event.getEntity().getLocation());
        final FlagPermissions world = plugin.getWorldFlags().getPerms(event.getEntity().getWorld().getName());
        if (entity == EntityType.CREEPER) {
            if (!perms.has("creeper", perms.has("explode", true))) {
                cancel = true;
            }
        }
        if (entity == EntityType.PRIMED_TNT || entity == EntityType.MINECART_TNT) {
            if (!perms.has("tnt", perms.has("explode", true))) {
                cancel = true;
            }
        }
        if (entity == EntityType.FIREBALL) {
            if (!perms.has("fireball", perms.has("explode", true))) {
                cancel = true;
            }
        }
        if (entity == EntityType.SMALL_FIREBALL) {
            if (!perms.has("fireball", perms.has("explode", true))) {
                cancel = true;
            }
        }
        if (entity == EntityType.WITHER_SKULL || entity == EntityType.WITHER) {
            if (!perms.has("wither", perms.has("explode", world.has("wither", world.has("explode", true))))) {
                cancel = true;
            }
        }
        if (cancel) {
            event.setCancelled(true);
            event.getEntity().remove();
        } else {
            final List<Block> preserve = new ArrayList<Block>();
            for (final Block block : event.blockList()) {
                final FlagPermissions blockperms = plugin.getPermsByLoc(block.getLocation());
                if ((!blockperms.has("wither", blockperms.has("explode", world.has("wither", world.has("explode", true)))) && (entity == EntityType.WITHER || entity == EntityType.WITHER_SKULL)
                        || (!blockperms.has("fireball", blockperms.has("explode", true)) && (entity == EntityType.FIREBALL || entity == EntityType.SMALL_FIREBALL))
                        || (!blockperms.has("tnt", blockperms.has("explode", true)) && (entity == EntityType.PRIMED_TNT || entity == EntityType.MINECART_TNT))
                        || (!blockperms.has("creeper", blockperms.has("explode", true)) && entity == EntityType.CREEPER))) {
                    preserve.add(block);
                }
            }
            for (final Block block : preserve) {
                event.blockList().remove(block);
            }
        }
    }

    @EventHandler(priority = EventPriority.LOWEST)
    public void onEntityInteract(final EntityInteractEvent event) {
        final Block block = event.getBlock();
        final Material mat = block.getType();
        final Entity entity = event.getEntity();
        final FlagPermissions perms = plugin.getPermsByLoc(block.getLocation());
        final boolean hastrample = perms.has("trample", perms.has("hasbuild", true));
        if (!hastrample && !(entity.getType() == EntityType.FALLING_BLOCK) && (mat == Material.SOIL || mat == Material.SOUL_SAND)) {
            event.setCancelled(true);
        }
    }

    @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
    public void onExplosionPrime(final ExplosionPrimeEvent event) {
        final EntityType entity = event.getEntityType();
        final FlagPermissions perms = plugin.getPermsByLoc(event.getEntity().getLocation());
        if (entity == EntityType.CREEPER) {
            if (!perms.has("creeper", perms.has("explode", true))) {
                event.setCancelled(true);
                event.getEntity().remove();
            }
        }
        if (entity == EntityType.PRIMED_TNT || entity == EntityType.MINECART_TNT) {
            if (!perms.has("tnt", perms.has("explode", true))) {
                event.setCancelled(true);
                event.getEntity().remove();
            }
        }
        if (entity == EntityType.FIREBALL) {
            if (!perms.has("fireball", perms.has("explode", true))) {
                event.setCancelled(true);
                event.getEntity().remove();
            }
        }
        if (entity == EntityType.SMALL_FIREBALL) {
            if (!perms.has("fireball", perms.has("explode", true))) {
                event.setCancelled(true);
                event.getEntity().remove();
            }
        }
        if (entity == EntityType.WITHER_SKULL) {
            if (!perms.has("witherdamage", perms.has("damage", true))) {
                event.setCancelled(true);
                event.getEntity().remove();
            }
        }
    }

    @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
    public void onHangingBreak(final HangingBreakEvent event) {
        if (event instanceof HangingBreakByEntityEvent) {
            final HangingBreakByEntityEvent evt = (HangingBreakByEntityEvent) event;
            if (evt.getRemover() instanceof Player) {
                final Player player = (Player) evt.getRemover();
                if (plugin.isResAdminOn(player)) {
                    return;
                }
                final String pname = player.getName();
                final FlagPermissions perms = plugin.getPermsByLocForPlayer(event.getEntity().getLocation(), player);
                final String world = event.getEntity().getWorld().getName();
                if (!perms.playerHas(pname, world, "destroy", perms.playerHas(pname, world, "build", true))) {
                    event.setCancelled(true);
                    player.sendMessage(ChatColor.RED + plugin.getLanguage().getPhrase("NoPermission"));
                }
            }
        }
    }

    @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
    public void onHangingPlace(final HangingPlaceEvent event) {
        final Player player = event.getPlayer();
        if (plugin.isResAdminOn(player)) {
            return;
        }
        final FlagPermissions perms = plugin.getPermsByLocForPlayer(event.getEntity().getLocation(), player);
        final String pname = player.getName();
        final String world = player.getWorld().getName();
        if (!perms.playerHas(pname, world, "place", perms.playerHas(pname, world, "build", true))) {
            event.setCancelled(true);
            player.sendMessage(ChatColor.RED + plugin.getLanguage().getPhrase("NoPermission"));
        }
    }

    @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
    public void onSplashPotion(final PotionSplashEvent event) {
        if (event.isCancelled()) {
            return;
        }
        final Entity ent = event.getEntity();
        final boolean srcpvp = plugin.getPermsByLoc(ent.getLocation()).has("pvp", true);
        final Iterator<LivingEntity> it = event.getAffectedEntities().iterator();
        while (it.hasNext()) {
            final LivingEntity target = it.next();
            if (target.getType() == EntityType.PLAYER) {
                final Boolean tgtpvp = plugin.getPermsByLoc(target.getLocation()).has("pvp", true);
                if (!srcpvp || !tgtpvp) {
                    event.setIntensity(target, 0);
                }
            }
        }
    }
}
