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

import eu.jonahbauer.wizard.client.libgdx.Client;
import eu.jonahbauer.wizard.client.libgdx.screens.LobbyScreen;
import eu.jonahbauer.wizard.common.messages.data.SessionData;
import eu.jonahbauer.wizard.common.messages.server.*;
import lombok.Getter;
import lombok.Setter;

import java.util.Optional;

public final class Lobby extends BaseState {
    
    private SessionListMessage list;
    private LobbyScreen lobbyScreen;

    @Getter
    @Setter
    private String playerName = "";
    
    public Lobby(SessionListMessage list) {
        this.list = list;
    }
    
    @Override
    public Optional<ClientState> onEnter(Client client) {
        lobbyScreen = new LobbyScreen(client.getGame());
        client.getGame().setScreen(lobbyScreen);
        lobbyScreen.setSessions(list.getSessions().toArray(new SessionData[0]));
        
        list = null;
        return super.onEnter(client);
    }
    
    @Override
    public Optional<ClientState> onMessage(Client client, ServerMessage message) {
        if (message instanceof SessionCreatedMessage created) {
            lobbyScreen.addSession(created.getSession());
            return Optional.empty();
        } else if (message instanceof SessionRemovedMessage removed) {
            lobbyScreen.removeSession(removed.getSession());
            return Optional.empty();
        } else if (message instanceof SessionModifiedMessage modified) {
            lobbyScreen.modifySession(modified.getSession());
            return Optional.empty();
        } else if (message instanceof SessionListMessage list) {
            lobbyScreen.setSessions(list.getSessions().toArray(new SessionData[0]));
            return Optional.empty();
        } else {
            return unexpectedMessage(client, message);
        }
    }
}