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

import eu.jonahbauer.wizard.client.cli.Client;
import eu.jonahbauer.wizard.client.cli.commands.MenuCommand;
import eu.jonahbauer.wizard.common.messages.server.ServerMessage;
import lombok.SneakyThrows;
import org.java_websocket.framing.CloseFrame;

import java.util.Optional;

public final class Menu extends BaseState {

    @Override
    @SneakyThrows
    public Optional<ClientState> onEnter(Client client) {
        if (client.getSocket() != null && client.getSocket().isOpen()) {
            client.getSocket().close(CloseFrame.GOING_AWAY);
            client.waitForReady();
            return Optional.empty();
        }
        return super.onEnter(client);
    }

    @Override
    public Optional<ClientState> onMessage(Client client, ServerMessage message) {
        // it is possible that there are messages still queued after
        // returning to the menu as a result of a previous message
        return Optional.empty();
    }

    @Override
    public Optional<ClientState> onClose(Client client, int code, String reason, boolean remote) {
        client.ready();
        super.onClose(client, code, reason, remote);
        return Optional.empty();
    }

    @Override
    public Object getCommand() {
        return MenuCommand.class;
    }
}
