/// <reference lib="webworker" />
/* eslint-disable no-restricted-globals */

// This service worker can be customized!
// See https://developers.google.com/web/tools/workbox/modules
// for the list of available Workbox modules, or add any other
// code you'd like.
// You can also remove this file if you'd prefer not to use a
// service worker, and the Workbox build step will be skipped.

import { clientsClaim } from 'workbox-core'
import { precacheAndRoute } from 'workbox-precaching'

import { manifestParser } from './helpers/parseHlsResponse'

declare const self: ServiceWorkerGlobalScope

clientsClaim()

// Precache all of the assets generated by your build process.
// Their URLs are injected into the manifest variable below.
// This variable must be present somewhere in your service worker file,
// even if you decide not to use precaching. See https://cra.link/PWA
precacheAndRoute(self.__WB_MANIFEST)

// This allows the web app to trigger skipWaiting via
// registration.waiting.postMessage({type: 'SKIP_WAITING'})
self.addEventListener('message', (event) => {
  if (event.data && event.data.type === 'SKIP_WAITING') {
    self.skipWaiting()
  }
})
const sendDuration = async (clientId: string, response:Response) => {
  const client = await self.clients.get(clientId)
  if (!client) return
  const text = await response.text()
  const totalDuration = manifestParser(text)
  client.postMessage({ duration: totalDuration })
}
// Any other custom service worker logic can go here.
self.addEventListener('fetch', async (event) => {
  const regex = /m3u8/g
  if (regex.test(event.request.url)) {
    const getPlaylists = async () => {
      const response = await fetch(event.request)
      sendDuration(event.clientId, response.clone())
      return response
    }
    event.respondWith(getPlaylists())
  }
})
