package eu.mhsl.minenet.minigames.server.provider;

import eu.mhsl.minenet.minigames.util.UuidUtil;
import net.minestom.server.MinecraftServer;
import net.minestom.server.network.UuidProvider;
import net.minestom.server.network.player.PlayerConnection;
import net.minestom.server.utils.mojang.MojangUtils;

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

public class ByPlayerNameUuidProvider implements UuidProvider {
    @Override
    public UUID provide(PlayerConnection playerConnection, String username) {
        try {

            if(MinecraftServer.getConnectionManager().findOnlinePlayer(username) != null) throw new IllegalStateException();
            String client = MojangUtils.fromUsername(username).get("id").getAsString();
            return UuidUtil.unTrimm(client);

        } catch (NullPointerException e) {
            Logger.getGlobal().info("Player " + username + " is unknown by Mojang! (Using random UUID)");
        } catch (IllegalStateException e) {
            Logger.getGlobal().info("Player with the username " + username + " is already online.");
            playerConnection.disconnect();
        }

        return UUID.randomUUID();
    }
}
