// 缓存key
const CACHE_KEY = "OVO_TAB_CACHE"
// 需要缓存的资源 - 固定资源
const CACHE_LIST = [
  "https://www.waylon.online/static/ovo/font/ovo.woff2",
  "https://www.waylon.online/static/ovo/common/weather/xiayu.jpg",
  "https://www.waylon.online/static/ovo/common/weather/duoyun.jpg",
  "https://www.waylon.online/static/ovo/common/weather/xiaxue.jpg",
  "https://www.waylon.online/static/ovo/common/weather/yintian.jpg",
  "https://www.waylon.online/static/ovo/common/weather/qingtian.jpg"
]

// 侦听器
self.addEventListener("install", (event) => {
  // 添加缓存
  event.waitUntil(
    // 打开 CACHE_KEY 缓存空间并添加缓存列表
    caches
      .open(CACHE_KEY)
      .then((cache) => cache.addAll(CACHE_LIST))
      .catch((error) => console.error("Cache key error:", error))
  )
})
// 监听sw是否活跃
self.addEventListener("activate", (event) => {
  // 删除其他缓存空间
  event.waitUntil(
    caches.keys().then((cacheNames) => {
      return Promise.all(
        cacheNames.map((cacheName) => {
          if (![CACHE_KEY].includes(cacheName)) {
            return caches.delete(cacheName)
          }
        })
      )
    })
  )
})

// 在 fetch 事件中返回缓存的资源
self.addEventListener("fetch", (event) => {
  const url = event.request.url
  try {
    event.respondWith(
      caches.match(event.request).then((response) => {
        if (response) {
          return response
        }
        return fetch(event.request).then((response) => {
          // 动态与固定的资源分别存在不同的缓存空间
          const cacheKey = CACHE_KEY
          const isStaticResource = url.startsWith(
            "https://www.waylon.online/static/"
          )
          const isCSSResource = url.startsWith("https://www.waylon.online/css/")
          // 如果请求成功或者命中CDN\浏览器缓存，则缓存新的响应
          if (
            (isStaticResource || isCSSResource) &&
            [200, 304].includes(response.status)
          ) {
            const responseToCache = response.clone()
            caches.open(cacheKey).then((cache) => {
              cache.put(event.request, responseToCache)
            })
          }
          return response
        })
      })
    )
  } catch (e) {
    console.error("service worker fetch error:", e)
  }
})
