const APP_MAIN_FILE = 'app_46_24_03_06_30';

const CACHE = APP_MAIN_FILE;

const PRECACHE_URLS = [
  './imgs/fonts/css/font-awesome.min.css',
  './sma/rc/style/sma.css',
  './sma/rc/style/viewer.css',
  './logo.png',
  './imgs/loading.png',
  './imgs/logon.png',
  './sma/dojo/resources/blank.gif',
  './sma/config.js',
  './sma/services/Services.js',
  './sma/def.js',
  './sma/' + APP_MAIN_FILE + '.js'
];

self.addEventListener('message', evt => {
  const url = evt.data.replace(/\\/g, '/');
  const key = '.' + url.substr(url.lastIndexOf('/'));

  caches.open(CACHE).then(cache => {
    cache.match(key).then((response) => {
      if (response == null) {
        cache.add(key); 
      }
    });
  });
}); 

self.addEventListener('install', evt => {
  let lang = './sma/nls/app_';

  switch (navigator.language.toLowerCase()) {
    case 'en': {
      lang += 'en-us.js';
      break;
    }
    default: {
      lang += navigator.language ? navigator.language.toLowerCase() + '.js' : 'en-us.js';
      break;
    }
  }

  PRECACHE_URLS.push(lang);

  evt.waitUntil(
    caches.open(CACHE)
    .then(cache => cache.addAll(PRECACHE_URLS))
    .then(() => self.skipWaiting())
  );
});

// Delete any cache that has the prefix as the app file name
// that does not match with the current cache version
self.addEventListener('activate', evt => {
  evt.waitUntil(
    caches.keys().then(cacheNames => {
      return cacheNames.filter(cache => {
        return cache !== CACHE && cache.indexOf('app_') !== -1;
      });
    })
    .then(cachesToDelete => {
      return Promise.all(
        cachesToDelete.map(cacheToDelete => caches.delete(cacheToDelete))
      );
    })
    .then(() => self.clients.claim())
  );
});

self.addEventListener('fetch', evt => {
  if (evt.request.url.startsWith(self.location.origin)) {
    evt.respondWith(
      caches.match(evt.request, {
        cacheName: CACHE
      }).then(cachedResponse => {
        if (cachedResponse) {
          return cachedResponse;
        }

        return fetch(evt.request).then(response => { return response; });
      })
    );
  }
});