var ws = null;

var index = 0;

var url = "";

var firstLoad = true;

var run = true;

var forcedClose = false;

var reconnectDelay = 2000;

var cmd_close_ws = "close_ws";
var cmd_ipc_error = "ipc_error";

self.addEventListener("message", function(msg) {
    // console.log("new message " + msg.data.command + msg.data.index);
    if (firstLoad) {
        if (msg.data.command === "wsUrl") {
            index = msg.data.index;
            url = msg.data.url;
            firstLoad = false;
            // console.log("first load of DW" + index);
            createWebSocket();
        }
    } else {
        switch (msg.data.command) {
            case "closeWs":
                forcedClose = true;
                ws.close();
                break;
            case "openWs":
                if (forcedClose === true) {
                    forcedClose = false;
                    // console.log("openWs");
                    createWebSocket();
                }
                break;
            default:
                if (ws.readyState === WebSocket.OPEN)
                    ws.send(msg.data.data);
                break;
        }

    }
});

function createWebSocket() {
    if (ws === null || ws.readyState === WebSocket.CLOSED) {
        // console.log("Creating new WS" + index + " @ " + url);
        ws = new WebSocket(url);
        ws.onmessage = function wsOnMessage(event) {
            if (event.data === "ERROR: IPC Service unreachable: org.freedesktop.DBus.Error.ServiceUnknown") {
                let com = new Object();
                let ret = new Object();
                ret.command = cmd_ipc_error;
                com.data = event.data;
                ret.data = com;
                ret.index = index;
                postMessage(ret);
            } else {
                try {
                    let com = JSON.parse(event.data);
                    let ret = new Object();
                    ret.command = com.command;
                    ret.data = event.data;
                    ret.index = index;
                    postMessage(ret);
                } catch {
                    console.log("JSON parse error");
                }
            }

            return false;
        };

        ws.onopen = function wsOnOpen(event) {
            // console.log("Open WS" + index + " @ " + url);
            var str = "[ \"channels\", \"groups\", \"settings\", \"speaker_presets\"]";
            // var str = "[ \"channels\", \"groups\", \"settings\", \"speaker_presets 0 xover_hp_filter\", \"speaker_presets 0 xover_lp_filter\", \"speaker_presets 1 xover_hp_filter\", \"speaker_presets 1 xover_lp_filter\", \"speaker_presets 2 xover_hp_filter\", \"speaker_presets 2 xover_lp_filter\", \"speaker_presets 3 xover_hp_filter\", \"speaker_presets 3 xover_lp_filter\"]";
            ws.send("[{\"command\":\"subscribe\",\"arg4\":" + str + "}]");
            ws.send("[{\"command\":\"oem_get_status\",\"arg1\":0}]");
        };

        ws.onerror = function(event) {
            console.log("WS" + index + " onerror : " + event);
            ws.close();
        };

        ws.onclose = function(event) {
            let ret = new Object();
            ret.command = cmd_close_ws;
            ret.index = index;
            postMessage(ret);
            // console.log("WS" + index + " onclose");
            if (!forcedClose) {
                setTimeout(function() {
                    createWebSocket();
                }, reconnectDelay);
            }
        };
    }
}