import { englishPage } from "./language"
const md5 = require('./lib-md5.js')

async function handleRequest(request) {
    let {pathname} = new URL(request.url)
    pathname = pathname.toLowerCase()
    if (pathname.endsWith('/')) {
        pathname = pathname.substring(0, pathname.length - 1);
    }
    
    if (pathname === '/func-vars.html') {
        return new Response(englishPage(request) ? HOMEPAGE_EN : HOMEPAGE, {headers: {"Content-Type": "text/html; charset=utf-8"}})
    } else if (pathname === '/func-vars') {
        const body = await request.json()
        const varName = body.varName
        if (!varName) {
            return new Response("Please enter the variable name")
        }
        // In this example, the variable name is passed in as a string by the client, so it needs to be accessed in a special way: const value = window["VAR-NAME"]
        // In a real scenario, it can be accessed directly: const value = VAR-NAME
        const varValue = window[varName]
        if (varValue === undefined) {
            return new Response("The variable does not exist")
        } else {
            return new Response(varValue)
        }
    }
}



const HOMEPAGE_EN = `
<html>
<head>
<title>Function Variable Lookup</title>
<style>
body {
font-family: Arial, sans-serif;
}
h1 {
color: #333;
text-align: center;
}
.container {
max-width: 400px;
margin: 0 auto;
}
input[type="text"] {
width: 100%;
height: 40px;
padding: 8px;
font-size: 16px;
border: 1px solid #ccc;
}
.btn {
display: inline-block;
padding: 10px 20px;
background-color: #333;
color: #fff;
font-size: 16px;
border: none;
cursor: pointer;
}
.response {
margin-top: 20px;
border: 1px solid #ccc;
padding: 10px;
}
</style>
</head>
<body>
<div class="container">
<h1>Function Variable Lookup</h1>
<input type="text" id="urlInput" placeholder="Enter variable name">
<br><br>
<button class="btn" onclick="searchShortLink()">Lookup</button>
<div class="response">
<p id="responseText"></p>

<script>
    function shortLink(action) {
        var varName = document.getElementById("urlInput").value;
        var data = JSON.stringify({ action: action, varName: varName });

        var xhr = new XMLHttpRequest();
        xhr.open("POST", "/func-vars/");
        xhr.setRequestHeader("Content-type", "application/json");
        xhr.onreadystatechange = function() {
            if (xhr.readyState === XMLHttpRequest.DONE) {
                if (xhr.status === 200) {
                    document.getElementById("responseText").innerHTML = xhr.responseText;
                } else {
                    document.getElementById("responseText").innerHTML = "Operation failed: " + xhr.responseText;
                }
            }
        };
        xhr.send(data);
    }

    function searchShortLink() {
        shortLink("search")
    }
</script>
</body>
</html>
`
                    
addEventListener("fetch", event => {
    return event.respondWith(handleRequest(event.request))
})