package rip.tilly.bedwars.listeners.game;

import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerMoveEvent;
import rip.tilly.bedwars.BedWars;
import rip.tilly.bedwars.game.Game;
import rip.tilly.bedwars.game.GameState;
import rip.tilly.bedwars.events.PlayerKillEvent;
import rip.tilly.bedwars.playerdata.PlayerData;
import rip.tilly.bedwars.playerdata.PlayerState;

public class MovementListener implements Listener {

    private final BedWars plugin = BedWars.getInstance();

    private boolean isInGame(PlayerData playerData) {
        return playerData.getPlayerState() == PlayerState.PLAYING;
    }

    @EventHandler
    public void onPlayerMove(PlayerMoveEvent event) {
        Player player = event.getPlayer();
        if (player.getGameMode() == GameMode.CREATIVE && player.isOp()) {
            return;
        }

        PlayerData playerData = this.plugin.getPlayerDataManager().getPlayerData(player.getUniqueId());
        if (playerData == null) {
            this.plugin.getLogger().warning(player.getName() + "'s player data is null");
            return;
        }

        if (playerData.getPlayerState() == PlayerState.RESPAWNING) {
            return;
        }

        if (!this.isInGame(playerData)) {
            return;
        }

        Game game = this.plugin.getGameManager().getGame(player.getUniqueId());
        if (game == null) {
            return;
        }

        Location to = event.getTo();
        Location from = event.getFrom();
        if (to.getX() != from.getX() || to.getZ() != from.getZ()) {
            if (game.getGameState() == GameState.STARTING) {
                player.teleport(from);
                return;
            }
        }

        if (from.getBlockY() <= game.getArena().getDeadZone() && game.getGameState() != GameState.ENDING && playerData.getPlayerState() != PlayerState.RESPAWNING) {
            Player killer = playerData.getLastDamager();
            if (killer != null) {
                this.plugin.getServer().getPluginManager().callEvent(new PlayerKillEvent(player, killer));
            } else {
                this.plugin.getServer().getPluginManager().callEvent(new PlayerKillEvent(player, null));
            }
        }
    }
}
