import { englishPage } from "./language"

async function handleRequest(request) {
    let response = await fetch(request)
    response.headers.set("X-Version", "petshop-v1")
    if (isFromChrome(request) && isHtml(response)) {
        console.log("rewrite page")
        let body = await response.text()
        const en = englishPage(request)
        body = body.replace('Make Your Pets Happy', 
            en ? ':::R:::E:::W:::R:::I:::T:::T:::E:::N:::' : '::::我::::被::::改::::写::::了::::')
        body = body.replace('Dolore tempor clita lorem rebum kasd eirmod dolore diam eos kasd.', 
            en ? 'Only when accessed using Chrome browser will the text be rewritten.</br>For other browsers, the original text will be displayed.</br>' : '只有用Chrome浏览器访问才会改写</br>其他浏览器访问将显示原文</br>')
        response.headers.delete('ETag')
        response.headers.delete('Last-Modified')
        return new Response(body, response);
    } else {
        console.log("pass page")
        return response
    }
}

function isFromChrome(request) {
    let userAgent = request.headers.get("User-Agent")
    return userAgent && userAgent.toLowerCase().includes("chrome")
}

function isHtml(response) {
    let contentType = response.headers.get("Content-Type")
    return contentType && contentType.toLowerCase().includes("text/html")
}
                    
addEventListener("fetch", event => {
    return event.respondWith(handleRequest(event.request))
})