package net.mc_pandacraft.java.plugin.pandacraftutils.modules.cheat_protect;

import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.entity.ThrownExpBottle;
import org.bukkit.entity.Vehicle;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.ExpBottleEvent;
import org.bukkit.event.vehicle.VehicleCreateEvent;

import net.mc_pandacraft.java.plugin.pandacraftutils.ConfigManager;
import net.mc_pandacraft.java.plugin.pandacraftutils.PandacraftUtils;

public class EntitySpamManager implements Listener {
	
	private PandacraftUtils plugin = PandacraftUtils.getInstance();
	
	public EntitySpamManager() {
		plugin.getServer().getPluginManager().registerEvents(this, plugin);
	}
	
	
	
	/*
	 * Non pris en charge pour le moment
	@EventHandler
	public void onCreatureSpawn(CreatureSpawnEvent event) {
		
	}
	*/
	
	
	/**
	 * Prends en charge l'évènement de création d'un véhicule, et programme sa destruction
	 * si le chunk dans lequel il se trouve dépasse le nombre d'entité autorisé
	 * @param event
	 */
	@EventHandler
	public void onVehicleCreate(VehicleCreateEvent event) {
		Vehicle v = event.getVehicle();
		Location l = v.getLocation();
		if (!isInWorld(l)) return;
		if (containsTooManyEntity(l.getChunk()))
		{
			plugin.getServer().getScheduler().runTaskLater(plugin, new Runnable() {
				private Vehicle vehicle;
				public Runnable init(Vehicle v) {
					vehicle = v;
					return this;
				}
				@Override
				public void run() {
					vehicle.remove();
				}
			}.init(v), 1);
		}
		
	}
	
	
	@EventHandler
	public void onExpBottle(ExpBottleEvent event) {
		ThrownExpBottle b = event.getEntity();
		if (!isInWorld(b.getLocation())) return;
		if (containsTooManyEntity(b.getLocation().getChunk())) {
			event.setExperience(0);
		}
	}
	
	
	
	
	
	
	
	
	private boolean isInWorld(Location l) {
		World w = l.getWorld();
		String config = ConfigManager.getInstance().EntitySpam_worlds;
		String[] worlds = config.split(";");
		for (String ws : worlds)
			if (w.getName().equalsIgnoreCase(ws))
				return true;
		return false;
		
	}
	
	private boolean containsTooManyEntity(Chunk c) {
		if (!c.isLoaded()) c.load();
		Entity[] ents = c.getEntities();
		return (ents.length > ConfigManager.getInstance().EntitySpam_limitPerChunks);
	}
	
}
