package eu.jonahbauer.wizard.client.libgdx;

import com.badlogic.gdx.Gdx;
import eu.jonahbauer.wizard.common.messages.server.ServerMessage;
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;

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) {
        if (WizardGame.DEBUG) {
            System.out.println("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) {
        e.printStackTrace();
        close(CloseFrame.ABNORMAL_CLOSE, e.getMessage());
    }

    @Override
    public void send(String text) {
        if (WizardGame.DEBUG) {
            System.out.println("Sending: " + text);
        }
        super.send(text);
    }

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

