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);
              }
            } else if (typeof event.data  === 'object' &&  event.data.message === 'offlinePendingDocumentsCount') {
                const swEvent = new CustomEvent('offlinePendingDocumentsCountFromServiceWorker', {'detail': event.data.data} );
                window.document.dispatchEvent(swEvent);
            }

            return;
        });

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

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

              logger.info('Service Worker update detected!');
              const newSw = reg.installing;

              if (reg.active !== null){
                var url = '/clientConfig/displayUpgradePrompt';
                var xmlHttp = new XMLHttpRequest();
                xmlHttp.open( "GET", url, false );
                xmlHttp.send( null );
                if(xmlHttp.responseText === 'true'){
                  const myCustomEvent = new CustomEvent('service-worker-update-found',  {detail: {newSW: newSw}});
                  document.dispatchEvent(myCustomEvent);
                } else {
                  newSw.postMessage('InstallingUpdatedServiceWorker');
                }
              } else {
                newSw.postMessage('InstallingServiceWorker');
              }

              const clientConfig = window.ftClientConfig;
              newSw.postMessage({ type: 'config', clientConfig });

              const divSWUpdateIndicator =  document.getElementById('swUpdateProgressIndicator');
              if (divSWUpdateIndicator) {
                divSWUpdateIndicator.style.opacity='1';
                divSWUpdateIndicator.style.height='auto';
                divSWUpdateIndicator.click();
              }


              newSw.onstatechange = function () {
                switch (newSw.state) {
                  case 'installed':
                    logger.info('Service Worker installed!');
                    break;

                  case 'redundant':
                    if (divSWUpdateIndicator) {
                      divSWUpdateIndicator.style.opacity='0';
                      divSWUpdateIndicator.style.height='0';
                      divSWUpdateIndicator.click();
                    }

                }
              };
            });
        }, function error(err) {
            logger.error(err);
        });
    });
}
