// Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
const CACHE_VERSION = { 'version': '0.0.213' };
const dataCacheName = 'jubileeData-v1';
const cacheName = 'jubilee-final-1';
const filesToCache = [
  '/',
  '/index.html',
  '/service-worker.js',
  '/site.webmanifest',
  '/browserconfig.xml',
  '/css/mui.custom.css',
  '/js/bundle.js',
  '/js/vendor.js',
  '/img/favicon-16x16.png',
  '/img/favicon-32x32.png',
  '/img/android-chrome-192x192.png',
  '/img/android-chrome-512x512.png',
  '/gfx/stars_00.png',
  '/gfx/stars_10.png',
  '/gfx/stars_15.png',
  '/gfx/stars_20.png',
  '/gfx/stars_25.png',
  '/gfx/stars_30.png',
  '/gfx/stars_35.png',
  '/gfx/stars_40.png',
  '/gfx/stars_45.png',
  '/gfx/stars_50.png',
  '/gfx/yssdk_yelp_logo.png',
  '/gfx/bg_evening.jpg',
  '/gfx/bg_morning.jpg',
  '/gfx/clear_d.jpg',
  '/gfx/clear_n.jpg',
  '/gfx/cloudy_d.jpg',
  '/gfx/cloudy_n.jpg',
  '/gfx/foggy_d.jpg',
  '/gfx/foggy_n.jpg',
  '/gfx/rain_d.jpg',
  '/gfx/rain_n.jpg',
  '/gfx/snow_d.jpg',
  '/gfx/snow_n.jpg',
  '/gfx/storm_d.jpg',
  '/gfx/storm_n.jpg'
];

self.addEventListener('install', function(e) {
  console.log('[ServiceWorker] Install');
  e.waitUntil(
    caches.open(cacheName).then(function(cache) {
      console.log('[ServiceWorker] Caching app shell');

      return cache.addAll(filesToCache);
    })
  );
});

self.addEventListener('activate', function(e) {
  console.log('[ServiceWorker] Activate');
  e.waitUntil(
    caches.keys().then(function(keyList) {
      return Promise.all(keyList.map(function(key) {
        if (key !== cacheName && key !== dataCacheName) {
          console.log('[ServiceWorker] Removing old cache', key);

          return caches.delete(key);
        }
      }));
    })
  );

  /*
   * Fixes a corner case in which the app wasn't returning the latest data.
   * You can reproduce the corner case by commenting out the line below and
   * then doing the following steps: 1) load app for first time so that the
   * initial New York City data is shown 2) press the refresh button on the
   * app 3) go offline 4) reload the app. You expect to see the newer NYC
   * data, but you actually see the initial data. This happens because the
   * service worker is not yet activated. The code below essentially lets
   * you activate the service worker faster.
   */
  return self.clients.claim();
});

self.addEventListener('fetch', function(e) {
  console.warn('[Service Worker] Fetch', e.request.url);
  const dataUrl = '/getnexttraintimes?';
  if (e.request.url.indexOf(dataUrl) > -1) {
    console.log('!');

    /*
     * When the request URL contains dataUrl, the app is asking for fresh
     * weather data. In this case, the service worker always goes to the
     * network and then caches the response. This is called the "Cache then
     * network" strategy:
     * https://jakearchibald.com/2014/offline-cookbook/#cache-then-network
     */
    e.respondWith(
      caches.open(dataCacheName).then(function(cache) {
        return fetch(e.request).then(function(response) {
          cache.put(e.request.url, response.clone());

          return response;
        });
      })
    );
  }
  else

    /*
     * The app is asking for app shell files. In this scenario the app uses the
     * "Cache, falling back to the network" offline strategy:
     * https://jakearchibald.com/2014/offline-cookbook/#cache-falling-back-to-network
     */
    e.respondWith(
      caches.match(e.request).then(function(response) {
        return response || fetch(e.request);
      })
    );
});
