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 Map<UUID, SessionData> sessions = new HashMap<>();

    public Lobby(Collection<SessionData> sessions) {
        sessions.forEach(session -> this.sessions.put(session.getUuid(), session));
    }

    @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.put(session.getUuid(), session);
            return Optional.empty();
        } else if (message instanceof SessionRemovedMessage removed) {
            sessions.remove(removed.getSession());
            return Optional.empty();
        } else if (message instanceof SessionModifiedMessage modified) {
            var session = modified.getSession();
            sessions.put(session.getUuid(), session);
            return Optional.empty();
        } else if (message instanceof SessionListMessage list) {
            sessions.clear();
            list.getSessions().forEach(session -> sessions.put(session.getUuid(), session));
            return Optional.empty();
        } else {
            return unexpectedMessage(client, message);
        }
    }

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