var CACHE_NAME = 'prefeitura-resolve-v1900';
var APP_BASE = '/prefeitura-resolve/public';
var URLS_TO_CACHE = [
  APP_BASE + '/index.php',
  APP_BASE + '/manifest.json',
  APP_BASE + '/assets/css/style.css',
  APP_BASE + '/assets/css/public.css',
  APP_BASE + '/assets/css/public-mobile.css',
  APP_BASE + '/assets/js/public-mobile.js',
  APP_BASE + '/assets/js/mapa.js',
  APP_BASE + '/assets/img/icon-192.png',
  APP_BASE + '/assets/img/icon-512.png'
];

self.addEventListener('install', function (event) {
  event.waitUntil(
    caches.open(CACHE_NAME).then(function (cache) {
      return cache.addAll(URLS_TO_CACHE);
    }).catch(function () {
      return Promise.resolve();
    })
  );
  self.skipWaiting();
});

self.addEventListener('activate', function (event) {
  event.waitUntil(
    caches.keys().then(function (keys) {
      return Promise.all(keys.map(function (key) {
        if (key !== CACHE_NAME) {
          return caches.delete(key);
        }
      }));
    })
  );
  self.clients.claim();
});

self.addEventListener('fetch', function (event) {
  if (event.request.method !== 'GET') {
    return;
  }

  var requestUrl = new URL(event.request.url);
  var routeParam = requestUrl.searchParams.get('route') || '';
  var isAdminRequest = requestUrl.pathname.indexOf(APP_BASE + '/index.php') === 0 &&
    routeParam.indexOf('/admin') === 0;
  var isRefreshRequest = requestUrl.searchParams.has('_refresh');

  if (isAdminRequest || isRefreshRequest) {
    event.respondWith(fetch(event.request, { cache: 'no-store' }).catch(function () {
      return caches.match(APP_BASE + '/index.php');
    }));
    return;
  }

  event.respondWith(
    caches.match(event.request).then(function (cached) {
      if (cached) {
        return cached;
      }
      return fetch(event.request).then(function (response) {
        if (!response || response.status !== 200 || response.type !== 'basic') {
          return response;
        }
        var responseToCache = response.clone();
        caches.open(CACHE_NAME).then(function (cache) {
          cache.put(event.request, responseToCache);
        });
        return response;
      }).catch(function () {
        return caches.match(APP_BASE + '/index.php');
      });
    })
  );
});
