import { englishPage } from "./language"

async function handleRequest(request) {
    let {pathname} = new URL(request.url.toLowerCase())
    if (pathname.endsWith('/'))  pathname = pathname.substring(0, pathname.length - 1)
    
    if (pathname === '/m3u8-video.html') {
        return new Response(englishPage(request) ? HOMEPAGE_EN : HOMEPAGE, 
                    {headers: {"Content-Type": "text/html; charset=utf-8"}})
    }

    pathname = pathname.substring("/m3u8-video".length)

    const kv = new EdgeKV({namespace: englishPage(request) ? "edge_site_appletv1" : "edge_site_appletv2"})
    const resp = await kv.get(pathname, {type: "stream"})
    if (resp == null) {
        return new Response("Page not found", {status: 404})
    }

    const contentType = contentTypeOfFile(pathname)

    return new Response(resp, {headers: {"Content-Type": contentType}})
}

function contentTypeOfFile(fileName) {
    const ext = fileName.split('.').pop()
    switch (ext) {
        case 'm3u8':    return 'application/vnd.apple.mpegurl'
        case 'ts':      return 'video/mp2t'
        default:        return 'application/octet-stream'
    }
}



const HOMEPAGE_EN = `
<!DOCTYPE html>
<html>
<head>
  <title>M3U8 Video Playback</title>
  <link href="https://vjs.zencdn.net/7.11.4/video-js.min.css" rel="stylesheet">
</head>
<body>
  <video id="my-video" class="video-js" controls preload="auto" width="640" height="360">
    <source src="/m3u8-video/edge-site-appletv1.m3u8" type="application/x-mpegURL">
  </video>

  <script src="https://vjs.zencdn.net/7.11.4/video.min.js"></script>
  <script>
    var player = videojs('my-video');
  </script>
</body>
</html>
`
                    
addEventListener("fetch", event => {
    return event.respondWith(handleRequest(event.request))
})