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

import eu.jonahbauer.wizard.client.libgdx.Client;
import eu.jonahbauer.wizard.client.libgdx.WizardGame;
import eu.jonahbauer.wizard.client.libgdx.screens.ErrorScreen;
import eu.jonahbauer.wizard.common.messages.server.ServerMessage;
import lombok.extern.log4j.Log4j2;

import java.util.Optional;

@Log4j2
public abstract class BaseState implements ClientState {
    
    @Override
    public Optional<ClientState> onEnter(Client context) {
        return ClientState.super.onEnter(context);
    }
    
    @Override
    public Optional<ClientState> onOpen(Client client) {
        throw new IllegalStateException();
    }
    
    @Override
    public Optional<ClientState> onClose(Client client, int code, String reason, boolean remote) {
        if (remote) {
            log.error("Lost connection (code={}, reason={})", code, reason);
        } else {
            log.info("Connection closed (code={}, reason={})", code, reason);
        }
        return Optional.of(new Menu());
    }
    
    protected Optional<ClientState> unexpectedMessage(Client client, ServerMessage message) {
        // return to menu on unexpected message
        log.fatal("Unexpected message {}. Returning to menu.", message);
        showErrorScreen(client, "Unexpected message %s. Returning to menu.".formatted(message));
        return Optional.of(new Menu());
    }

    @Deprecated
    public void showErrorScreen(Client client, String message) {
        WizardGame game = client.getGame();
        client.setError(true);
        game.setScreen(new ErrorScreen(game, message));
    }

    public Optional<ClientState> dismissErrorScreen(Client client) {
        client.setError(false);
        return onErrorDismissed(client);
    }

    protected abstract Optional<ClientState> onErrorDismissed(Client client);
}
