import { englishPage } from "./language"

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 === '/edgekv.html') {
        return new Response(englishPage(request) ? HOMEPAGE_EN : HOMEPAGE, {headers: {"Content-Type": "text/html; charset=utf-8"}})
    } else if (pathname.startsWith('/edgekv/')) {
        return handleEdgeKV(request)
    }
}

async function handleEdgeKV(request) {
    let {pathname} = new URL(request.url)
    const method = request.method
    const key = pathname.substring(8)
    console.log('key', key)

    if (!key) {
        return new Response('Key cannot be empty', {status: 500})
    }

    const kv = new EdgeKV({namespace: "edgekv_crud_1"})

    if (method == 'PUT') {
        const value = await request.text()
        const expiration = Math.floor(new Date().getTime() / 1000) + 60 * 60 * 24 * 29
        await kv.put(key, value, {expiration: expiration})
        return new Response("")
    } else if (method == 'GET') {
        const value = await kv.get(key)
        if (value == null) {
            return new Response("Not found the key", {status: 500})
        }
        return new Response(value)
    } else if (method == 'DELETE') {
        await kv.delete(key)
        return new Response("")
    } else {
        return new Response("", {status: 400})
    }
}



const HOMEPAGE_EN = `
<!DOCTYPE html>
<html>
<head>
    <title>KV Data Management</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
    <h1>KV Data Management</h1>

    <h2>Search Data</h2>
    <label for="searchInput">Key:</label>
    <input type="text" id="searchInput">
    <button onclick="searchData()">Search</button>

    <h2>Update Data</h2>
    <label for="updateKeyInput">Key:</label>
    <input type="text" id="updateKeyInput">
    <label for="updateValueInput">Value:</label>
    <input type="text" id="updateValueInput">
    <button onclick="updateData()">Update</button>

    <h2>Delete Data</h2>
    <label for="deleteKeyInput">Key:</label>
    <input type="text" id="deleteKeyInput">
    <button onclick="deleteData()">Delete</button>

    <h2>Results</h2>
    <ul id="searchResults"></ul>

    <script>
        const baseURL = "/edgekv/";

        function searchData() {
            const keyword = $("#searchInput").val();

            const results = $("#searchResults");
            results.empty();

            $.ajax({
                url: baseURL + keyword,
                type: "GET",
                success: function (result, status, xhr) {
                    results.append("<li>" +  "Search Success: " + xhr.responseText + "</li>");
                },
                error: function (xhr, status, error) {
                    results.append("<li>" +  "Search Failed: " + xhr.responseText + "</li>");
                }
            });
        }

        function updateData() {
            const key = $("#updateKeyInput").val();
            const value = $("#updateValueInput").val();

            const results = $("#searchResults");
            results.empty();

            $.ajax({
                url: baseURL + key,
                type: "PUT",
                data: value,
                success: function (result, status, xhr) {
                    results.append("<li>" +  "Update Success" + "</li>");
                },
                error: function (xhr, status, error) {
                    results.append("<li>" +  "Update Failed: " + xhr.responseText + "</li>");
                }
            });
        }

        function deleteData() {
            const key = $("#deleteKeyInput").val();

            const results = $("#searchResults");
            results.empty();

            $.ajax({
                url: baseURL + key,
                type: "DELETE",
                success: function (result, status, xhr) {
                    results.append("<li>" +  "Delete Success" + "</li>");
                },
                error: function (xhr, status, error) {
                    results.append("<li>" +  "Delete Failed: " + xhr.responseText + "</li>");
                }
            });
        }
    </script>
</body>
</html>
`
                    
addEventListener("fetch", event => {
    return event.respondWith(handleRequest(event.request))
})