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

import eu.jonahbauer.wizard.client.cli.Client;
import eu.jonahbauer.wizard.client.cli.state.AwaitingJoinLobby;
import eu.jonahbauer.wizard.client.cli.state.Session;
import eu.jonahbauer.wizard.common.messages.client.LeaveSessionMessage;
import eu.jonahbauer.wizard.common.messages.client.ReadyMessage;

import static picocli.CommandLine.*;

@Command(name = "\b", subcommands = {HelpCommand.class, QuitCommand.class})
public class SessionCommand {
    private final Client client;
    private final Session session;

    public SessionCommand(Client client, Session session) {
        this.client = client;
        this.session = session;
    }

    @Command(name = "ready")
    public void ready(
            @Parameters(index = "0", paramLabel = "<ready>", defaultValue = "true") boolean ready
    ) {
        session.setNextReady(ready);
        client.send(new ReadyMessage(ready));
        client.waitForReady();
    }

    @Command(name = "leave", description = "Leaves the current session and returns to the lobby")
    public AwaitingJoinLobby leave() {
        client.send(new LeaveSessionMessage());
        return new AwaitingJoinLobby();
    }

    @Command(name = "list", description = "Shows a list of players in the current session")
    public void list() {
        var players = session.getPlayers();
        var count = players.size();
        if (count > 0) {
            StringBuilder builder = new StringBuilder();

            if (count == 1) builder.append("There is one player in this session:\n");
            else builder.append("There are ").append(count).append(" players in this session:\n");

            players.forEach((id, session) -> builder.append(session).append('\n'));
            client.println(builder);
        } else {
            client.println("There are no players in this session.");
        }
    }
}
