const timestamp = '__timestamp__'
const ASSETS = `cache${timestamp}`

// `shell` is an array of all the files generated by webpack,
// `assets` is an array of everything in the `assets` directory
const assets = __assets__.map(file => file.startsWith('/') ? file : `/${file}`)
const toCache = __shell__.concat(assets)
  .filter(filename => !filename.endsWith('.map'))
  .filter(filename => !filename.startsWith('/apple-icon'))
const cached = new Set(toCache)

// `routes` is an array of `{ pattern: RegExp }` objects that
// match the pages in your app
const routes = __routes__

self.addEventListener('install', event => {
  event.waitUntil((async function () {
    let cache = await caches.open(ASSETS)
    await cache.addAll(toCache)
    self.skipWaiting()
  })())
})

self.addEventListener('activate', event => {
  event.waitUntil((async function () {
    let keys = await caches.keys()
    // delete old caches
    for (let key of keys) {
      if (key !== ASSETS) {
        await caches.delete(key)
      }
    }
    await self.clients.claim()
  })())
})

const CACHE_FIRST = [
  '/system/accounts/avatars'
]

self.addEventListener('fetch', event => {
  const req = event.request
  const url = new URL(req.url)

  // don't try to handle e.g. data: URIs
  if (!url.protocol.startsWith('http')) {
    return
  }

  event.respondWith((async function () {
    // always serve assets and webpack-generated files from cache
    if (url.origin === self.origin && cached.has(url.pathname)) {
      return caches.match(req)
    }

    // for pages, you might want to serve a shell `index.html` file,
    // which Sapper has generated for you. It's not right for every
    // app, but if it's right for yours then uncomment this section

    if (url.origin === self.origin &&
        routes.find(route => route.pattern.test(url.pathname))) {
      return caches.match('/index.html')
    }

    // For these GET requests, go cache-first
    if (req.method === 'GET' &&
        CACHE_FIRST.some(pattern => url.pathname.startsWith(pattern))) {
      let cache = await caches.open(`offline${timestamp}`)
      let response = await cache.match(req)
      if (response) {
        // update asynchronously
        fetch(req).then(response => {
          cache.put(req, response.clone())
        })
        return response
      }
      response = await fetch(req)
      cache.put(req, response.clone())
      return response
    }

    // for everything else, go network-only
    return fetch(req)
  })())
})
