const CACHE_NAME = 'MeeChat_v1.3';
let urlsToCache = [];
// let networkFirstList = ['', 'h5.html', 'mini.html'];
let networkFirstList = [];

self.addEventListener('install', function (event) {
  self.skipWaiting();
  console.log('[ServiceWorker] install')
  event.waitUntil(
    caches.open(CACHE_NAME).then(function(caches){
      console.log('open cache:' + CACHE_NAME);
      let allList = urlsToCache.concat(networkFirstList)
      return caches.addAll(allList);
    })
  )
})

self.addEventListener('activate', function (event) {
  console.log('[ServiceWorker] activate')
  // 只保留白名单的版本
  const cacheWhitelist = [CACHE_NAME];
  event.waitUntil(
    caches.keys().then(function(cacheNames) {
      return Promise.all(
        cacheNames.map(function(cacheName) {
          console.log('遍历缓存：' + cacheName)
          if (cacheWhitelist.indexOf(cacheName) === -1) {
            console.log('删除缓存：' + cacheName)
            return caches.delete(cacheName)
          }
        })
      )
    })
  )
})

self.addEventListener('fetch', function (event) {
  // console.log('[ServiceWorker] Fetch', event.request.url)
  let url = event.request.url.replace(location.origin, '')
  url = url.replace('https:', '')
  let pos = url.indexOf('#')
  if (pos > 0) {
    url = url.substr(0, pos)
  }

  let isNetworkFirst = url.endsWith('.html') || url.endsWith('.json');
  if (urlsToCache.indexOf(url) !== -1 && !isNetworkFirst) {
    return _cacheFirst(event)
  } else {
    return _networkFirst(event)
  }
})

function _cacheFirst(event) {
  event.respondWith(
    caches.match(event.request).then(function (response) {
      // Cache hit - return response
      if (response) {
        return response;
      }

      return fetch(event.request);
    })
  );
}

function _networkFirst(event) {
  event.respondWith(
      fetch(event.request).then((response) => {
        // console.log('[ServiceWorker] network first, request: ', event.request.url);
        return response
      }).catch (() => {
        caches.match(event.request).then(function (response) {
          // Cache hit - return response
          if (response) {
            // console.log('[ServiceWorker] cache first, From cache:', event.request.url)
            return response;
          }

          // console.log('[ServiceWorker] cache first, From network:', event.request.url)
          return fetch(event.request);
        })
      })
  );
}

self.addEventListener('error', function (event) {
  console.log('[ServiceWorker] error', event)
})

self.addEventListener('push', function (event) {
  console.log('[Service Worker] 收到通知', event);
  function decodeUnicode (str) {
    str = str.replace(/\\/g, '%')
    str = unescape(str)
    str = str.replace(/%/g, '\\')
    str = str.replace(/\\/g, '')
    return str
  }

  let data = JSON.parse(event.data.text())
  const title = decodeUnicode(data.title)
  const options = {
    body: decodeUnicode(data.content),
    icon: 'img/icons/meechat.png',
    tag: data.tag,
    data: data.data,
  }
  event.waitUntil(self.registration.showNotification(title, options))
})

// 点击跳转
self.addEventListener('notificationclick', function (event) {
  console.log('[Service Worker] 点击通知', event);
  let data = event.notification.data
  let url = data && data.url || 'https://mee.chat/'

  event.notification.close()
  event.waitUntil(
      clients.openWindow(url)
  )
})
