import { ClientMessage, ServerMessage } from "../Data.js";
import { MainScene } from "./MainScene.js";

export interface WebsocketMessageListener {
    onMessage(message: any): void;
}



export class WebSocketController {

    connection: WebSocket;
    connectionReady: boolean = false;

    constructor(private messageListener: WebsocketMessageListener, onWebSocketReady?: (controller: WebSocketController) => void) {

        let url: string = (window.location.protocol.startsWith("https") ? "wss://" : "ws://") + window.location.host;
        this.connection = new WebSocket(url);

        let that = this;

        this.connection.onopen = function () {
            that.connectionReady = true;

            if(onWebSocketReady != null){
                onWebSocketReady(that);
            }
        };

        this.connection.onmessage = function (message) {
            try {
                var serverMessage: ServerMessage = JSON.parse(message.data);
            } catch (e) {
                console.log('This doesn\'t look like a valid JSON: ',
                    message.data);
                return;
            }

            that.messageListener.onMessage(serverMessage);

        };

    }

    public send(message: ClientMessage) {
        if(!this.connectionReady) return;
        this.connection.send(JSON.stringify(message));
    }



}