package eu.mhsl.minenet.minigames.handler.global;

import eu.mhsl.minenet.minigames.Main;
import eu.mhsl.minenet.minigames.api.QueuedPlayerRooms;
import eu.mhsl.minenet.minigames.instance.room.Room;
import eu.mhsl.minenet.minigames.instance.transfer.Transfer;
import eu.mhsl.minenet.minigames.skin.SkinCache;
import eu.mhsl.minenet.minigames.util.MoveInstance;
import net.minestom.server.MinecraftServer;
import net.minestom.server.entity.Player;
import eu.mhsl.minenet.minigames.instance.hub.Hub;
import net.minestom.server.event.EventListener;
import net.minestom.server.event.player.AsyncPlayerConfigurationEvent;
import net.minestom.server.network.packet.server.play.TeamsPacket;
import net.minestom.server.scoreboard.Team;
import net.minestom.server.timer.TaskSchedule;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.configurate.serialize.SerializationException;

import java.util.Objects;
import java.util.UUID;
import java.util.logging.Logger;

public class PlayerLoginHandler implements EventListener<AsyncPlayerConfigurationEvent> {
    public static final Team globalTeam = MinecraftServer.getTeamManager()
        .createBuilder("global")
        .collisionRule(TeamsPacket.CollisionRule.NEVER)
        .build();

    @Override
    public @NotNull Class<AsyncPlayerConfigurationEvent> eventType() {
        return AsyncPlayerConfigurationEvent.class;
    }

    @Override
    public @NotNull Result run(@NotNull AsyncPlayerConfigurationEvent event) {
        Player p = event.getPlayer();

        Transfer transferInstance = new Transfer();
        p.setRespawnPoint(transferInstance.getSpawn());
        event.setSpawningInstance(transferInstance);

        UUID pushQueue = QueuedPlayerRooms.pullQueue(event.getPlayer().getUuid());

        MinecraftServer.getSchedulerManager().scheduleTask(
            () -> {
                p.setTeam(globalTeam);
                if(pushQueue != null) {
                    Room.setRoom(p, Room.getRoom(pushQueue).orElseThrow());
                } else {
                    MoveInstance.move(p, Hub.INSTANCE);
                }
            },
            TaskSchedule.seconds(1),
            TaskSchedule.stop()
        );

        SkinCache.applySkin(p);

        try {
            if(Objects.requireNonNull(Main.globalConfig.node("admins").getList(String.class)).stream().anyMatch(s -> s.equalsIgnoreCase(p.getUsername()))) {
                p.setPermissionLevel(4);
            }
        } catch (SerializationException | NullPointerException ignored) {}

        Logger.getLogger("user").info(p.getUsername() + " joined");

//        new ChatMessage(Icon.SCIENCE).appendStatic("unübersetzter Jointext: ").appendStatic(p.getUsername()).send(MinecraftServer.getConnectionManager().getOnlinePlayers());

        return Result.SUCCESS;
    }
}
