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.server)
                break;

            websocket = new WebSocket(ev.data.server);
            websocket.addEventListener('open', function(ev) {
                postMessage({
                    act: 'ws:open',
                    type: ev.type,
                    timeStamp: ev.timeStamp,
                    isTrusted: ev.isTrusted,
                });
            });
            websocket.addEventListener('close', function(ev) {
                postMessage({
                    act: 'ws:close',
                    type: ev.type,
                    timeStamp: ev.timeStamp,
                    isTrusted: ev.isTrusted,
                    code: ev.code,
                    reason: ev.reason,
                    wasClean: ev.wasClean,
                });
            });
            websocket.addEventListener('error', function(ev) {
                postMessage({
                    act: 'ws:error',
                    type: ev.type,
                    timeStamp: ev.timeStamp,
                    isTrusted: ev.isTrusted,
                });
            });
            websocket.addEventListener('message', function(ev) {
                postMessage({
                    act: 'ws:message',
                    type: ev.type,
                    timeStamp: ev.timeStamp,
                    isTrusted: ev.isTrusted,
                    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:intervals':
            postMessage({
                act: 'ws:intervals',
                intervals: intervals,
            });
            break;

        case 'ws:send_interval':
            (function(interval, text) {
                intervals.push(setInterval(function() {
                    if(websocket)
                        websocket.send(text);
                }, interval));
            })(ev.data.interval, ev.data.text);
            break;

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