

self.activeList = {};

function guid() {
    return new Date().getTime();
}

self.addEventListener("install", function (i_event) {
    i_event.waitUntil(self.skipWaiting());
});

self.addEventListener("message", function (i_event) {

    var b_reload = true;
    var o_data = i_event.data || {};
    var s_guid = o_data.id || guid();

    if (o_data.action == "newtab") {
        s_guid = guid();
        b_reload = false;
    }

    var o_active = self.activeList[s_guid] || {};

    if (o_data.action == "reloadtab" || o_data.action == "newtab") {
        o_active.clientId = i_event.source.id;

        self.activeList[s_guid] = o_active;

        var a_clean = [];
        var o_list = self.activeList || {};
        var a_list = Object.keys(o_list);

        i_event.waitUntil(self.clients.matchAll().then(function (a_clients) {

            a_list.forEach(function (s_key) {

                var o_config = o_list[s_key];

                var b_found = false;

                a_clients.forEach(function (i_client) {

                    if (o_config.clientId == i_client.id) {
                        b_found = true;
                        return false;
                    }
                });

                if (!b_found) {
                    a_clean.push(s_key);
                    delete o_active[s_key];
                }
            });


            i_event.source.postMessage({
                action: "updatetab",
                buid: s_guid,
                count: a_clients.length,
                reload: b_reload,
                remove: a_clean
            });

        }));
    }

    if (o_data.action == "close") {

        self.clients.matchAll().then(function (a_clients) {

            a_clients.forEach(function (i_client) {

                i_client.postMessage({
                    action: "cleanup",
                    buid: s_guid,
                    reload: false
                });
            });
        });
    }
});
