let websocket, intervals = [];

addEventListener('message', function(ev) {
    if(!ev || !ev.data || !ev.data.act)
        return;

    switch(ev.data.act) {
        case 'ws:open':
            if(!ev.data.url)
                break;

            websocket = new WebSocket(ev.data.url);
            websocket.addEventListener('open', function(ev) {
                postMessage({ act: 'ws:open' });
            });
            websocket.addEventListener('close', function(ev) {
                postMessage({
                    act: 'ws:close',
                    detail: {
                        code: ev.code,
                        reason: ev.reason,
                        wasClean: ev.wasClean,
                    },
                });
            });
            websocket.addEventListener('error', function(ev) {
                postMessage({ act: 'ws:error' });
            });
            websocket.addEventListener('message', function(ev) {
                postMessage({
                    act: 'ws:message',
                    detail: {
                        data: ev.data,
                        origin: ev.origin,
                        lastEventId: ev.lastEventId,
                    },
                });
            });
            break;

        case 'ws:close':
            for(const interval of intervals)
                clearInterval(interval);
            if(!websocket)
                break;
            websocket.close();
            websocket = null;
            intervals = [];
            break;

        case 'ws:send':
            if(!websocket)
                break;
            websocket.send(ev.data.text);
            break;

        case 'ws:send_interval':
            (function(interval, text) {
                const intervalId = setInterval(function() {
                    if(websocket) {
                        websocket.send(text);
                        postMessage({ act: 'ws:call_interval', detail: { id: intervalId } });
                    }
                }, interval);

                intervals.push(intervalId);
                postMessage({ act: 'ws:create_interval', detail: { id: intervalId } });
            })(ev.data.interval, ev.data.text);
            break;

        case 'ws:clear_intervals':
            for(const interval of intervals)
                clearInterval(interval);
            intervals = [];
            break;
    }
});
