package poppy.modules;

import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.block.Block;
import org.bukkit.plugin.Plugin;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.meta.CompassMeta;
import org.bukkit.scheduler.BukkitRunnable;

public class FastTravelModule implements Listener {

	public static final int COUNTDOWN_TIME = 5;

	private Plugin plugin;

	public FastTravelModule(final Plugin plugin) {
		this.plugin = plugin;
	}

	@EventHandler
	public void onPlayerInteract(final PlayerInteractEvent event) {
		if (event.getHand() != EquipmentSlot.HAND) {
			return;
		}
		final ItemStack item = event.getItem();
		if (item == null || item.getType() != Material.COMPASS) {
			return;
		}
		final Block block = event.getClickedBlock();
		if (block != null && block.getType() == Material.LODESTONE) {
			return;
		}
		final CompassMeta meta = (CompassMeta) item.getItemMeta();
		if (!meta.hasLodestone()) {
			return;
		}
		final Player player = event.getPlayer();
		final Location location = meta.getLodestone();
		new BukkitRunnable() {
			int timer = COUNTDOWN_TIME;
			@Override
			public void run() {
				final Location playerLocation = player.getLocation();
				if ( timer > 0) {
					player.playSound(playerLocation, Sound.ENTITY_EXPERIENCE_ORB_PICKUP, 100.0F, 1.0F);
				}
				if (timer == 0) {
					this.cancel();
					location.add(0.5, 1.0, 0.5);
					location.setYaw(playerLocation.getYaw());
					location.setPitch(playerLocation.getPitch());
					player.teleport(location);
					player.playSound(playerLocation, Sound.ENTITY_PLAYER_TELEPORT, 100.0F, 1.0F);
				}
				timer--;
			}
		}.runTaskTimer(this.plugin, 0L, 20L);
	}
}
