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 lombok.extern.log4j.Log4j2;

import java.util.Optional;

@Log4j2
public final class AwaitingConnection extends Awaiting {
    
    @Override
    public Optional<ClientState> onEnter(Client client) {
        log.info("Awaiting connection...");
        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> onOpen(Client client) {
        log.info("Connection established.");
        return Optional.of(new AwaitingJoinLobby());
    }

    @Override
    public Optional<ClientState> onMessage(Client client, ServerMessage message) {
        return unexpectedMessage(client, message);
    }

    @Override
    public Optional<ClientState> onClose(Client client, int code, String reason, boolean remote) {
        log.error("Connection could not be established. (code={}, reason={}, remote={})", code, reason, remote);
        showErrorScreen(client, "Connection could not be established. (code=%d, reason=%s, remote=%b)".formatted(code, reason, remote));
        return Optional.of(new Menu());
    }

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