package hu.jgj52.pvpcore.Listeners;

import hu.jgj52.pvpcore.Main;
import org.bukkit.GameMode;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import org.bukkit.metadata.FixedMetadataValue;

public class SpectatorListener implements Listener {

    private final Main plugin;

    public SpectatorListener(Main plugin) {
        this.plugin = plugin;
    }

    @EventHandler
    public void onSpectatorTeleport(PlayerTeleportEvent event) {
        if (event.getPlayer().getGameMode() == GameMode.SPECTATOR && event.getCause() == TeleportCause.SPECTATE) {
            event.setCancelled(true);
        }
    }

    @EventHandler
    public void onPlayerQuit(PlayerQuitEvent event) {
        Player player = event.getPlayer();
        if (player.hasMetadata("IsSpectating") && player.getMetadata("IsSpectating").get(0).asBoolean()) {
            player.setMetadata("IsSpectating", new FixedMetadataValue(plugin, false));
        }
    }
}
