import { __awaiter, __generator } from "tslib";
/* eslint id-blacklist: 0 */
import { error as logError, warn } from '@dash4/log/build/browser';
var win = window;
var ws = new WebSocket("ws://localhost:" + win.dash4.port);
win.dash4 = win.dash4 || {};
win.dash4.socket = win.dash4.socket || {};
win.dash4.socket.isReady = false;
win.dash4.socket.readyList = [];
win.dash4.socket.listeners = {};
win.dash4.connectionCounter = typeof win.dash4.connectionCounter === 'number' ? win.dash4.connectionCounter : 0;
win.dash4.connectionLostCounter =
    typeof win.dash4.connectionLostCounter === 'number' ? win.dash4.connectionLostCounter : 0;
var listeners = win.dash4.socket.listeners;
var isReady = win.dash4.socket.isReady;
var readyList = win.dash4.socket.readyList;
function socketAbstract(wsInstace) {
    return {
        send: function (id, data) {
            wsInstace.send(JSON.stringify({
                id: id,
                data: data,
            }));
        },
        on: function (id, callback) {
            listeners[id] = { id: id, callback: callback };
        },
        off: function (id) {
            delete listeners[id];
        },
    };
}
function connected() {
    isReady = true;
    win.dash4.connectionCounter += 1;
    readyList.forEach(function (resolve) {
        resolve(socketAbstract(ws));
    });
    ws.onmessage = function (rawData) {
        var data = JSON.parse(rawData.data);
        Object.keys(listeners).forEach(function (key) {
            var _a = listeners[key], id = _a.id, callback = _a.callback;
            if (id !== data.id) {
                return;
            }
            callback(data.data);
        });
    };
}
win.onfocus = function () {
    if (win.dash4.connectionCounter !== win.dash4.connectionLostCounter) {
        return;
    }
    warn('client', "autoreload in 1 sec'}");
    setTimeout(function () {
        window.location.reload();
    }, 1000);
};
function disconnected() {
    warn('client', "connection closed");
    isReady = false;
    win.dash4.connectionLostCounter += 1;
}
function error() {
    logError('client', 'connection could not be established');
    isReady = false;
}
ws.onerror = error;
ws.onopen = connected;
ws.onclose = disconnected;
export function socket() {
    return __awaiter(this, void 0, void 0, function () {
        return __generator(this, function (_a) {
            return [2 /*return*/, new Promise(function (resolve) {
                    if (isReady) {
                        resolve(socketAbstract(ws));
                        return;
                    }
                    // if socket is not yet ready store resolve function in array
                    readyList.push(resolve);
                })];
        });
    });
}
//# sourceMappingURL=socket.js.map