package eu.jonahbauer.wizard.client.cli;

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) {
        getClient().onOpen();
    }

    @Override
    public void onMessage(String s) {
        ServerMessage message = ServerMessage.parse(s);
        getClient().onMessage(message);
    }

    @Override
    public void onClose(int i, String s, boolean b) {
        getClient().onClose(i, s, b);
    }

    @Override
    public void onError(Exception e) {
        getClient().println(e.getMessage());
        close(CloseFrame.ABNORMAL_CLOSE, e.getMessage());
    }

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