
//const sockJs = new SockJS("http://" + window.location.hostname + ":8999/ws/register.do");
//const sockJs = new SockJS("http://" + window.location.hostname + ":8999/ws/register.do", null, { transports: ["websocket", "xhr-streaming", "xhr-polling"] });

export class TWebSocket {
    constructor(clientType, recvFunc, disconnectFunc, errorFunc, connectFunc) {
        this.clientType = clientType;
        this.recvFunc = new Array();
        this.recvFunc.push(recvFunc);
        this.disconnectFunc = disconnectFunc;
        this.errorFunc = errorFunc;
        this.connectFunc = connectFunc;
        this.sockJs = null;
        this.connected = false;
    }

    connect() {
        console.log(`${this.clientType}: Websocket try connect`);

        const socket = new SockJS(_websocketUrl + "/ws/connect.do");
        this.sockJs = Stomp.over(socket);
        this.sockJs.connect(
            {}, // headers
            () => {
                // connected
                this.connected = true;
                console.log(`${this.clientType}: Websocket onConnected`);

                this.sockJs.subscribe(_websocketUrl + "/ws/messages.do", (payload) => {
                    // received
                    const recvMessage = JSON.parse(payload.body);
                    console.log(`${this.clientType}: Websocket onMessageReceived, `, payload);
                    console.log(`${this.clientType}: Websocket onMessageReceived, `, recvMessage);
                    this.recvFunc.forEach((func) => {
                        if (func) {
                            func(this.clientType, recvMessage);
                        }
                    });
                });

                if (this.connectFunc) {
                    this.connectFunc();
                }

                this.sendMessage("clientType", "connected");
            },
            (error) => {
                // errors
                this.connected = false;
                console.error(`${this.clientType}: Websocket onError: `, error);
                this.disconnect();
                if (this.disconnectFunc) {
                    this.disconnectFunc();
                }
            }
        );
    }

    disconnect() {
        if (this.sockJs) {
            this.sockJs.disconnect();
        }
        this.connected = false;
        console.log(`${this.clientType}: Websocket disconnect`);
    }

    sendMessage(ACommand, AMessage) {
        if (this.sockJs) {
            const sendMessage = JSON.stringify({ command: ACommand, message: AMessage });
            this.sockJs.send(_websocketUrl + "/ws/request.do", {}, sendMessage);
        } else {
            console.error(`${this.clientType}: Websocket already closed`);
        }
    }
}
