/* 
 * In EdgeKV, data is stored in the following format:
 *      | KEY            | VALUE        |
 *      | -------------- | ------------ |
 *      | /index.html    | Corresponding file data |
 *      | /img/about.jpg | Corresponding file data |
 * Assuming the requested URL is: http://www.test.com/catalog-z/index.html
 * We take the filename at the end, /index.html, as the key to retrieve the file data.
 */
async function handleRequest(request) {
    // Extract the requested filename from the URL
    let {pathname} = new URL(request.url.toLowerCase())
    if (pathname.endsWith('/'))  pathname = pathname.substring(0, pathname.length - 1)
    pathname = pathname.substring("/catalog-z".length)
    if (pathname === '') pathname = '/index.html'

    // Use the filename as the key to retrieve the file content from EdgeKV. Note that the namespace is the one we used previously to upload files, catalog-z
    const kv = new EdgeKV({namespace: "catalog_z2"})
    const content = await kv.get(pathname, {type: "stream"})
    if (content == null) {
        return new Response("Page not found", {status: 404}) // Respond with 404 if the file is not found
    }

    // Send the retrieved file content to the client
    const contentType = contentTypeOfFile(pathname) // Set the Content-Type based on the filename
    const headers = { 'Content-Type': contentType, 'Cache-Control': 'max-age=180' }
    console.log(`requested filename: ${pathname},content type: ${contentType}`) 
    return new Response(content, {headers: headers})
}

function contentTypeOfFile(fileName) {
    const ext = fileName.split('.').pop()
    switch (ext) {
        case 'html':    return 'text/html'
        case 'css':     return 'text/css'
        case 'js':      return 'application/javascript'
        case 'jpg':     return 'image/jpeg'
        case 'png':     return 'image/png'
        case 'mp4':     return 'video/mp4'
        case 'eot':     return 'application/vnd.ms-fontobject'
        case 'svg':
        case 'svgz':    return 'image/svg+xml'
        case 'woff':    return 'font/woff'
        case 'woff2':   return 'font/woff2'
        default:        return 'application/octet-stream'
    }
}
                    
addEventListener("fetch", event => {
    return event.respondWith(handleRequest(event.request))
})