package eu.jonahbauer.wizard.client.libgdx;

import com.badlogic.gdx.Gdx;
import eu.jonahbauer.wizard.common.messages.server.ServerMessage;
import lombok.extern.log4j.Log4j2;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.framing.CloseFrame;
import org.java_websocket.handshake.ServerHandshake;

import javax.net.ssl.SSLSocketFactory;
import java.net.URI;

@Log4j2
public class ClientSocket extends WebSocketClient {
    public ClientSocket(URI serverUri) {
        super(serverUri);
        
        if ("wss".equals(getURI().getScheme())) {
            setSocketFactory(SSLSocketFactory.getDefault());
        }
    }
    
    @Override
    public void onOpen(ServerHandshake serverHandshake) {
        Gdx.app.postRunnable(() -> getClient().onOpen());
    }
    
    @Override
    public void onMessage(String s) {
        log.debug("Received: {}", s);
        ServerMessage message = ServerMessage.parse(s);
        Gdx.app.postRunnable(() -> getClient().onMessage(message));
    }
    
    @Override
    public void onClose(int i, String s, boolean b) {
        Gdx.app.postRunnable(() -> getClient().onClose(i, s, b));
    }
    
    @Override
    public void onError(Exception e) {
        log.error("", e);
        close(CloseFrame.ABNORMAL_CLOSE, e.getMessage());
    }

    @Override
    public void send(String text) {
        log.debug("Sending: {}", text);
        super.send(text);
    }

    private Client getClient() {
        return getAttachment();
    }
}

