package eu.mhsl.minenet.minigames.instance.game.stateless.types.fastbridge;

import eu.mhsl.minenet.minigames.instance.Dimension;
import eu.mhsl.minenet.minigames.instance.game.stateless.StatelessGame;
import eu.mhsl.minenet.minigames.score.FirstWinsScore;
import net.minestom.server.coordinate.Pos;
import net.minestom.server.entity.GameMode;
import net.minestom.server.entity.Player;
import net.minestom.server.event.player.PlayerBlockPlaceEvent;
import net.minestom.server.event.player.PlayerMoveEvent;
import net.minestom.server.instance.Chunk;
import net.minestom.server.inventory.PlayerInventory;
import net.minestom.server.item.ItemStack;
import net.minestom.server.item.Material;
import org.jetbrains.annotations.NotNull;

public class Fastbridge extends StatelessGame {
    private int currentSpawn = 0;

    public Fastbridge() {
        super(Dimension.OVERWORLD.key, "Fastbridge", new FirstWinsScore());
        this.setGenerator(new FastbridgeChunkgenerator());
    }

    @Override
    protected void onPlayerMove(@NotNull PlayerMoveEvent playerMoveEvent) {
        Player player = playerMoveEvent.getPlayer();
        Pos newPos = playerMoveEvent.getNewPosition();
        if(this.getScore().hasResult(player)) return;
        if(newPos.y() < 0) {
            player.teleport(getSpawn());
            if(!isBeforeBeginning) this.resetPlayer(player);
        }
        if(newPos.x() > 53) {
            this.getScore().insertResult(player);
            player.setGameMode(GameMode.SPECTATOR);
        }
    }

    @Override
    protected void onStart() {
        getPlayers().forEach(player -> {
            player.setGameMode(GameMode.SURVIVAL);
            resetPlayer(player);
        });
    }

    @Override
    protected void onBlockPlace(@NotNull PlayerBlockPlaceEvent playerBlockPlaceEvent) {
        if(isBeforeBeginning) playerBlockPlaceEvent.setCancelled(true);
    }

    private void resetPlayer(Player player) {
        if(isBeforeBeginning) return;
        PlayerInventory inventory = player.getInventory();
        inventory.clear();
        inventory.addItemStack(ItemStack.of(Material.WHITE_WOOL, 64));
    }

    @Override
    public synchronized Pos getSpawn() {
        return new Pos(24, 1, currentSpawn++*Chunk.CHUNK_SIZE_Z*2-8, -90, 0);
    }
}
