import { waitingRoomSingle } from "./wslib-waiting-room-single"
import { englishPage } from "./language"

async function handleRequest(request) {
    const headers = request.headers
    const url = new URL(request.url)
    const clientID = headers.get("cdn-src-ip") + headers.get("user-agent") // Decided by the client to identify the access terminal
    if (!clientID) {
        return fetch(request)                           // Without terminal identifier, waiting room logic cannot be applied
    }
    const en = englishPage(request)
    const roomID = url.hostname                         // Decided by the client to determine which URL scope shares a waiting room
    const args = {
        connectedTimeout: 15,                           // The duration after which data inserted into the connection pool is automatically deleted
        connectedMax: 1,                                // The maximum number of allowed connected clients
        waitingTimeout: 30,                             // The duration after which data inserted into the waiting pool is automatically deleted
        waitingMax: 2,                                  // The maximum number of allowed waiting clients
        waitingPageMaxRefreshInterval: 3,               // The maximum interval for refreshing the waiting page
        generateWaitingPage: en ? enWaitingPage : null, // Customizable function to generate a waiting page; if not provided, the default page will be used
        generateBusyPage: null,                         // Customizable function to generate a busy page; if not provided, the default page will be used
    }

    const resp = await waitingRoomSingle(request, roomID, clientID, args)
    // For testing convenience, disable browser caching
    resp.headers.delete('ETag')
    resp.headers.delete('Last-Modified')
    return resp
}

function enWaitingPage(peopleFrontOfYou,  waitTime, refreshInterval) {
    const body = `<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Waiting Room</title>
<style>
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f2f2f2;
}

    h1 {
    font-size: 2rem;
    color: #5a5a5a;
    text-align: center;
    margin-bottom: 1rem;
    }

    .countdown {
    font-size: 1rem;
    color: #333;
    text-align: center;
    margin-top: 1rem;
    }

    .highlight {
    color: #2e86de;
    font-weight: bold;
    }
</style>
</head>
<body onload="countdown();">
<div class="container">
<h1>There are <span class="highlight">${peopleFrontOfYou}</span> people in front of you, estimated wait time <span class="highlight">${waitTime}</span> seconds</h1>
<div id="countdown" class="countdown">This page will refresh automatically in <span class="highlight">${refreshInterval}</span> seconds</div>
</div>

<script>
    function countdown() {
    let counter = ${refreshInterval-1};
    setInterval(() => {
        if(counter === 0) {
        location.reload();
        } else {
        document.getElementById('countdown').innerHTML = ` + '`This page will refresh automatically in <span class="highlight">${counter--}</span> seconds`;' + `
        }
    }, 1000);
    }
</script>
</body>
</html>`
    const headers = {"Content-Type": "text/html; charset=utf-8"}
    return new Response(body, {headers: headers})
}
                    
addEventListener("fetch", event => {
    return event.respondWith(handleRequest(event.request))
})