var logger = console;

var baseUrl = document.getElementsByTagName("base")[0].href.split('/')[3] || "";

// register the service worker as the first thing the app does. This intercepts requests for static assets and caches them so the
// version from cache will be loaded when offline
if ('serviceWorker' in navigator) {
    window.addEventListener('load', function() {
        navigator.serviceWorker.addEventListener('message', (event) => {
            const SERVICE_WORKER_ACTIVATED = 'service-worker-activated';
            if (event.data === 'service-worker-activated') {
                var isActivated = localStorage.getItem(baseUrl + SERVICE_WORKER_ACTIVATED);
                if (isActivated) {
                    window.location.reload();
                } else {
                    localStorage.setItem(baseUrl + SERVICE_WORKER_ACTIVATED, true);
                }
            }

            return;
        });

        var scope = baseUrl !== "" ? `/${baseUrl}/` : `/`;

        navigator.serviceWorker.register(`serviceWorker.js?baseUrl=${baseUrl}`, { scope: scope }).then(function success() {
            logger.info("Cache service worker registered.");
        }, function error(err) {
            logger.error(err);
        });
    });
}