//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`);

        this.sockJs = new SockJS(_apiUrl + "/ws/messages.do");
        this.sockJs.onopen = (message) => {
            console.log(`${this.clientType}: Websocket onopen, `, message);

            this.connected = true;
            if (this.connectFunc) {
                this.connectFunc(this.clientType, message);
            }
        };

        this.sockJs.onclose = (message) => {
            console.log(`${this.clientType}: Websocket onclose, `, message);

            this.connected = true;
            if (this.disconnectFunc) {
                this.disconnectFunc(this.clientType, message);
            }
        };

        this.sockJs.onerror = (message) => {
            console.log(`${this.clientType}: Websocket onerror, `, message);

            this.disconnect();
            if (this.errorFunc) {
                this.errorFunc(this.clientType, message);
            }
        };

        this.sockJs.onmessage = (payload) => {
            const recvMessage = JSON.parse(payload.data);
            console.log(`${this.clientType}: Websocket onmessage, `, recvMessage);
            this.recvFunc.forEach((func) => {
                if (func) {
                    func(this.clientType, recvMessage);
                }
            });
        };
    }

    disconnect() {
        if (this.sockJs) {
            this.sockJs.close();
        }
        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(_apiUrl + "/ws/request.do", {}, sendMessage);
        } else {
            console.error(`${this.clientType}: Websocket already closed`);
        }
    }
}
