package eu.jonahbauer.wizard.client.cli.state;

import eu.jonahbauer.wizard.client.cli.Client;
import eu.jonahbauer.wizard.common.messages.server.*;

import java.util.Optional;

public final class AwaitingJoinSession extends Awaiting {

    @Override
    public Optional<ClientState> onEnter(Client client) {
        client.println("Waiting for acknowledgment...");
        return super.onEnter(client);
    }

    @Override
    public Optional<ClientState> onMessage(Client client, ServerMessage message) {
        if (message instanceof SessionJoinedMessage joined) {
            return Optional.of(new Session(joined));
        } else if (message instanceof NackMessage nack) {
            switch (nack.getCode()) {
                case NackMessage.GAME_ALREADY_STARTED -> client.println("Error: Game has already started.");
                case NackMessage.SESSION_FULL -> client.println("Error: The session is full.");
                case NackMessage.SESSION_NOT_FOUND -> client.println("Error: Session not found.");
                case NackMessage.NAME_TAKEN -> client.println("Error: Name already taken.");
                default -> { return super.onMessage(client, message); }
            }
            return Optional.of(new AwaitingJoinLobby());
        } else if (message instanceof SessionModifiedMessage || message instanceof SessionRemovedMessage) {
            // drop
            return Optional.empty();
        } else {
            return super.onMessage(client, message);
        }
    }
}
