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

import eu.jonahbauer.wizard.client.cli.Client;
import eu.jonahbauer.wizard.client.cli.commands.LobbyCommand;
import eu.jonahbauer.wizard.common.messages.data.SessionData;
import eu.jonahbauer.wizard.common.messages.server.*;
import lombok.Getter;

import java.util.*;

public final class Lobby extends BaseState {
    @Getter
    private final Set<SessionData> sessions = new HashSet<>();

    public Lobby(SessionListMessage list) {
        sessions.addAll(list.getSessions());
    }

    @Override
    public Optional<ClientState> onEnter(Client client) {
        if (sessions.size() == 1) {
            client.println("Successfully joined the server. There is one open session.");
        } else {
            client.printfln("Successfully joined the server. There are %d open sessions.", sessions.size());
        }
        return super.onEnter(client);
    }

    @Override
    public Optional<ClientState> onMessage(Client client, ServerMessage message) {
        if (message instanceof SessionCreatedMessage created) {
            var session = created.getSession();
            sessions.add(session);
            return Optional.empty();
        } else if (message instanceof SessionRemovedMessage removed) {
            sessions.remove(new SessionData(removed.getSession(), null, 0, null));
            return Optional.empty();
        } else if (message instanceof SessionModifiedMessage modified) {
            sessions.remove(modified.getSession());
            sessions.add(modified.getSession());
            return Optional.empty();
        } else if (message instanceof SessionListMessage list) {
            sessions.clear();
            sessions.addAll(list.getSessions());
            return Optional.empty();
        } else {
            return unexpectedMessage(client, message);
        }
    }

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