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

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

import java.util.Optional;

public abstract class BaseState implements ClientState {

    @Override
    public Optional<ClientState> onEnter(Client context) {
        context.ready();
        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) {
            client.printfln("Lost connection (code=%d, reason=%s).", code, reason);
        } else {
            client.printfln("Connection closed (code=%d, reason=%s).", code, reason);
        }
        return Optional.of(new Menu());
    }

    protected static Optional<ClientState> unexpectedMessage(Client client, ServerMessage message) {
        // return to menu on unexpected message
        client.println("Fatal: Unexpected message " + message + ". Returning to menu.");
        if (client.isVerbose()) {
            new Exception().printStackTrace();
        }
        return Optional.of(new Menu());
    }
}
