import picAudit from "./wslib-audit"
import { englishPage } from "./language"

async function handleRequest(request) {
    let {pathname, host} = new URL(request.url.toLowerCase())
    if (pathname.endsWith('/'))  pathname = pathname.substring(0, pathname.length - 1)

    if (pathname === '/audit-examples.html') {
        let page = englishPage(request) ? HOMEPAGE_EN : HOMEPAGE
        page = page.replace('$[{host}]', host)
        return new Response(page, {headers: {"Content-Type": "text/html; charset=utf-8"}})
    } else {
        const data = await request.json()

        // Input parameter validation
        if (!data.url) {
            return new Response('Please enter the image URL!')
        }
        return picAudit(data.url)
    }
}




const HOMEPAGE_EN = `
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Image Audit Example</title>
    <style>
        body {
            background-color: #f3f3f3;
            display: flex;
            justify-content: center;
            font-family: Arial, sans-serif;
            padding-top: 20px; /* Add some padding at the top to avoid content sticking to the browser edge */
            // min-height: 50vh; /* Ensure the body has at least the height of the viewport */
        }

        .container {
            border: 1px solid #ccc;
            padding: 20px;
            background-color: #fff;
        }

        .input-container {
            margin-bottom: 20px;
        }

        .input-container label {
            display: block;
            margin-bottom: 5px;
        }

        .input-container input {
            width: 490px;
            padding: 5px;
            font-size: 14px;
        }

        .button {
            background-color: #0088cc;
            color: #fff;
            padding: 10px;
            border: none;
            cursor: pointer;
            border-radius: 4px;
            font-size: 14px;
        }

        .image-container {
            margin-top: 20px;
        }

        .image-container img {
            max-width: 100%;
            height: auto;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="input-container">
            <label for="imageUrl">Image URL</label>
            <input type="text" id="imageUrl" value="http://$[{host}]/image/p2405761558.jpg">
        </div>
        <div class="input-container">
            <button class="button" onclick="startAudit()">Image Moderation</button>
        </div>
        <div class="image-container" id="resultContainer"></div>
    </div>

    <script>
        function startAudit() {
            var resultContainer = document.getElementById("resultContainer");
            var labels = resultContainer.querySelectorAll('label');  
            labels.forEach(function(label) {  
                label.remove();  
            });
            var imageUrl = document.getElementById("imageUrl").value;
            var data = {
                url: imageUrl,
            };

            fetch("/audit-examples", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json"
                },
                body: JSON.stringify(data)
            }).then(response => {
                if (!response.ok) {
                  throw new Error('Network response was not ok');
                }
                return response.json(); // Convert response to JSON format
              })
              .then(jsonData => {
                console.log(jsonData); // Example output of JSON data
                var label_text = "neutral";
                var score = -1;
                for (var i = 0; i < jsonData.data.length; i++) {
                    var item = jsonData.data[i];
                    if (score < item.probability) {
                        label_text = item.result;
                        score = item.probability;
                    }
                }
                var resultContainer = document.getElementById("resultContainer");
                    var label = document.createElement("label")
                    label.style.wordBreak = "break-word";
                    label.style.maxWidth = "500px";
                    label.style.display = "inline-block";
                    label.style.color = "blue";
                    label.textContent = "Moderation Result:   " + label_text;
                    resultContainer.appendChild(label);
              })
              .catch(error => {
                // Error handling
                console.error('Fetch error:', error);
              });
        }
    </script>
</body>
</html>
`
                    
addEventListener("fetch", event => {
    return event.respondWith(handleRequest(event.request))
})