package eu.jonahbauer.wizard.client.libgdx;

import eu.jonahbauer.wizard.client.libgdx.state.ClientState;
import eu.jonahbauer.wizard.client.libgdx.state.Menu;
import eu.jonahbauer.wizard.common.machine.TimeoutContext;
import eu.jonahbauer.wizard.common.messages.client.ClientMessage;
import eu.jonahbauer.wizard.common.messages.server.ServerMessage;
import lombok.Getter;
import lombok.extern.log4j.Log4j2;

@Log4j2
public class Client extends TimeoutContext<ClientState, Client> {
    
    @Getter
    private final WizardGame game;
    
    @Getter
    private ClientSocket socket;
    
    public Client(WizardGame game) {
        super(new Menu());
        this.game = game;
    }
    
    @Override
    protected void handleError(Throwable t) {
        // TODO better error handling
        t.printStackTrace();
    }
    
    public void setSocket(ClientSocket socket) {
        this.socket = socket;
        if (socket != null) {
            this.socket.setAttachment(this);
        }
    }
    
    public void onOpen() {
        execute(s -> s.onOpen(this));
    }
    
    public void onClose(int code, String reason, boolean remote) {
        execute(s -> s.onClose(this, code, reason, remote));
    }
    
    public void onMessage(ServerMessage message) {
        log.debug(message.toString());
        execute(s -> s.onMessage(this, message));
    }
    
    @Override
    protected void onTransition(ClientState from, ClientState to) {
        System.out.println("Transistion from " + from.getClass().getSimpleName() + " to " + to.getClass().getSimpleName());
    }
    
    public void send(ClientMessage message) {
        getSocket().send(message.toString());
    }
}