package eu.mhsl.minenet.minigames.score.tournament;

import eu.mhsl.minenet.minigames.Resource;
import eu.mhsl.minenet.minigames.instance.Dimension;
import eu.mhsl.minenet.minigames.instance.MineNetInstance;
import eu.mhsl.minenet.minigames.instance.Spawnable;
import eu.mhsl.minenet.minigames.message.Icon;
import eu.mhsl.minenet.minigames.message.type.ChatMessage;
import net.minestom.server.MinecraftServer;
import net.minestom.server.coordinate.Pos;
import net.minestom.server.entity.*;
import net.minestom.server.event.player.PlayerMoveEvent;
import net.minestom.server.instance.anvil.AnvilLoader;

import java.util.List;

public class TournamentDisplay extends MineNetInstance implements Spawnable {
    private final List<Player> places;
    private final Tournament tournament;

    private final Pos[] placePositions = new Pos[] {
            new Pos(8.5, -56, 22.5, 180, 0),
            new Pos(12.5, -57, 20.5, 180, 0),
            new Pos(4.5, -58, 20.5, 180, 0)
    };

    public TournamentDisplay(Tournament tournament) {
        super(Dimension.OVERWORLD.key);
        setChunkLoader(new AnvilLoader(Resource.RESULT_DISPLAY.getPath()));
        this.places = tournament.getPlaces();
        this.tournament = tournament;

        this.places.forEach(player -> player.setGameMode(GameMode.ADVENTURE));

        eventNode().addListener(PlayerMoveEvent.class, playerMoveEvent -> {
            if(isOnDisplay(playerMoveEvent.getPlayer()) && !playerMoveEvent.getNewPosition().sameBlock(placePositions[getRankPosition(playerMoveEvent.getPlayer())])) {
                playerMoveEvent.setCancelled(true);
            }
        });
    }

    private boolean isOnDisplay(Player player) {
        if(getRankPosition(player) == -1) return false;
        return getRankPosition(player) < this.placePositions.length;
    }

    private int getRankPosition(Player player) {
        return this.places.indexOf(player);
    }

    @Override
    protected boolean onPlayerJoin(Player p) {
        MinecraftServer.getSchedulerManager().scheduleNextTick(() -> {
            if(isOnDisplay(p)) {
                p.sendMessage("You are on Display!");
                p.teleport(placePositions[getRankPosition(p)]);
            }
        });
        new ChatMessage(Icon.STAR)
                .numberedList(this.places.stream().map(player -> String.format("%s - %s Punkte", player.getUsername(), tournament.getGameScores().get(player))).toList())
                .send(p);
        return false;
    }

    @Override
    public Pos getSpawn() {
        return new Pos(8.5, -59, 11.5);
    }
}
