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.ServerMessage;
import eu.jonahbauer.wizard.common.messages.server.SessionListMessage;
import lombok.extern.log4j.Log4j2;

import java.util.Optional;

@Log4j2
public final class AwaitingJoinLobby extends Awaiting {
    
    @Override
    public Optional<ClientState> onEnter(Client client) {
        log.info("Waiting for session list...");
        if (!client.isError()) showScreen(client);
        return super.onEnter(client);
    }

    @Override
    public Optional<ClientState> onErrorDismissed(Client client) {
        showScreen(client);
        return Optional.empty();
    }

    @Override
    public Optional<ClientState> onMessage(Client client, ServerMessage message) {
        if (message instanceof SessionListMessage list) {
            log.info("There are {} open sessions.", list.getSessions().size());
            return Optional.of(new Lobby(list.getSessions()));
        } else {
            return unexpectedMessage(client, message);
        }
    }

    private void showScreen(Client client) {
        client.getGame().setScreen(new LoadingScreen(client.getGame(), "menu.loading.joining_lobby"));
    }
}
