package eu.jonahbauer.wizard.server.debug;

import eu.jonahbauer.wizard.common.messages.player.PlayerMessage;
import eu.jonahbauer.wizard.common.messages.server.NackMessage;
import eu.jonahbauer.wizard.common.messages.server.ServerMessage;
import eu.jonahbauer.wizard.common.model.Configuration;
import eu.jonahbauer.wizard.server.NackException;
import eu.jonahbauer.wizard.server.Session;
import eu.jonahbauer.wizard.server.machine.Player;

import java.util.UUID;

public class DebugSession extends Session {
    public DebugSession(UUID uuid, String name, long timeout, Configuration configuration) {
        super(uuid, name, timeout, configuration);

        var dummy1 = new SessionPlayer(new UUID(0, 1), "Dummy #1");
        var dummy2 = new SessionPlayer(new UUID(0, 2), "Dummy #2");
        var dummy3 = new SessionPlayer(new UUID(0, 3), "Dummy #3");
        var dummy4 = new SessionPlayer(new UUID(0, 4), "Dummy #4");
        getPlayers().put(dummy1.getUuid(), dummy1);
        getPlayers().put(dummy2.getUuid(), dummy2);
        getPlayers().put(dummy3.getUuid(), dummy3);
        getPlayers().put(dummy4.getUuid(), dummy4);
    }

    @Override
    public synchronized void handlePlayerMessage(UUID uuid, PlayerMessage message) {
        var player = getPlayers().get(uuid);
        if (player == null) {
            throw new NackException(NackMessage.PLAYER_NOT_FOUND, "Who are you?");
        }
    }

    public synchronized UUID join(Player player, String name) {
        if (getGame() != null) {
            throw new NackException(NackMessage.GAME_ALREADY_STARTED, "Game has already started.");
        } else if (getPlayers().size() == MAX_PLAYERS) {
            throw new NackException(NackMessage.SESSION_FULL, "Session is full.");
        } else if (getPlayers().values().stream().anyMatch(p -> p.getName().equalsIgnoreCase(name))) {
            throw new NackException(NackMessage.PLAYER_NAME_TAKEN, "Player name is already taken.");
        }

        SessionPlayer sessionPlayer;
        long i = 0;
        do {
            sessionPlayer = new SessionPlayer(new UUID(0, i++), name);
        } while (getPlayers().putIfAbsent(sessionPlayer.getUuid(), sessionPlayer) != null);
        sessionPlayer.setPlayer(player);

        notifyJoined(sessionPlayer.toData());
        notifyLobby();

        return sessionPlayer.getUuid();
    }

    @Override
    protected void startGame() {}

    @Override
    public void notifyPlayers(ServerMessage message) {
        super.notifyPlayers(message);
    }

    @Override
    public boolean isDebug() {
        return true;
    }
}
