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

import eu.jonahbauer.wizard.client.libgdx.Client;
import eu.jonahbauer.wizard.client.libgdx.screens.LoadingScreen;
import eu.jonahbauer.wizard.common.messages.server.*;
import eu.jonahbauer.wizard.common.model.Configuration;
import lombok.Getter;
import lombok.RequiredArgsConstructor;

import java.util.Optional;
import java.util.UUID;

@Getter
@RequiredArgsConstructor
public final class AwaitingJoinSession extends Awaiting {

    private final UUID session;
    private final String sessionName;
    private final Configuration configuration;
    private final String playerName;

    @Override
    public Optional<ClientState> onEnter(Client client) {
        System.out.println("Waiting for acknowledgment...");
        client.getGame().setScreen(new LoadingScreen(client.getGame()));
        return super.onEnter(client);
    }

    @Override
    public Optional<ClientState> onMessage(Client client, ServerMessage message) {
        if (message instanceof SessionJoinedMessage joined) {
            if (session != null && !session.equals(joined.getSession())) throw new RuntimeException();
            return Optional.of(new Session(joined, sessionName, configuration, playerName));
        } else if (message instanceof NackMessage nack) {
            switch (nack.getCode()) {
                case NackMessage.GAME_ALREADY_STARTED -> System.out.println("Error: Game has already started.");
                case NackMessage.SESSION_FULL -> System.out.println("Error: The session is full.");
                case NackMessage.SESSION_NOT_FOUND -> System.out.println("Error: Session not found.");
                case NackMessage.NAME_TAKEN -> System.out.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);
        }
    }
}
