import { englishPage } from "./language"\r\n

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

    if (pathname === '/iot-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"}})
    } 
    return new Response('Not Found', {
        status: 404,
        statusText: 'Not Found',
        headers: {
          'Content-Type': 'text/plain',
        },
      });
}


const HOMEPAGE_EN = `
<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Audio Recorder</title>
    <style>
        body {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100vh;
            margin: 0;
            background-color: #f0f0f0;
            font-family: Arial, sans-serif;
        }

        #recordButton {
            padding: 10px 20px;
            font-size: 16px;
            margin: 20px;
            cursor: pointer;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 5px;
            transition: background-color 0.3s;
        }

        #recordButton:hover {
            background-color: #45a049;
        }

        #audioPlayer {
            margin-top: 20px;
        }

        #cmdValues {
            margin-top: 20px;
            padding: 10px;
            width: 80%;
            max-width: 500px;
            background-color: #fff;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            text-align: center;
        }
    </style>
</head>
<body>
    <button id="recordButton">Start Recording</button>
    <audio id="audioPlayer" controls></audio>
    <div id="cmdValues">CMD_values will be displayed here.</div>

    <script>
        let mediaRecorder;
        let audioChunks = [];
        let last_request_id = "";
        const cmd_list = ["stop massage",
        "resume massage",
        "Seat adjustment, lowering legs and lifting back",
        "Seat adjustment, lifting legs and tilting back",
        "Massage intensity, reduced intensity",
        "Massage intensity, increased intensity",
        "Move the massage wheel position up",
        "Leg massage activated",
        "Lumbar massage activated",
        "Back massage activated",
        "Full body massage activated",
        "Head and neck massage activated",
        "Foot massage activated"]


        function generateRandomString(length) {
            const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
            let result = '';
            for (let i = 0; i < length; i++) {
                const randomIndex = Math.floor(Math.random() * characters.length);
                result += characters.charAt(randomIndex);
            }
            return result;
        }

        document.getElementById('recordButton').addEventListener('click', async () => {
            if (!mediaRecorder || mediaRecorder.state === 'inactive') {
                // Start Recording
                const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
                mediaRecorder = new MediaRecorder(stream);

                mediaRecorder.ondataavailable = event => {
                    audioChunks.push(event.data);
                };

                mediaRecorder.onstop = async () => {
                    const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
                    audioChunks = [];  // Clear the chunks for the next recording
                    const randomRequestId = generateRandomString(16); 
                    const headers = {
                            'Content-Type': 'audio/wav',
                        };

                    if (last_request_id && last_request_id.trim().length > 0) {
                        headers['Last-Request-Id'] = last_request_id;
                    }

                    // Send the audio data to the server
                     const response = await fetch('https://ecatest.haplat.net/lcltest/', {
                        method: 'POST',
                        body: audioBlob,
                        headers: headers
                    });
                    
                    last_request_id = response.headers.get('X-Ws-Request-Id');
                    const CMD_value = response.headers.get('CMD_value');
                    const num = parseInt(CMD_value, 10); 
                    const cmdDisplay = document.getElementById('cmdValues');
                    if (CMD_value !== null) {
                        if ((num <= cmd_list.length) && (num > 0)){
                            cmdDisplay.textContent = 'CMD_value: ' + cmd_list[num-1];
                        } else {
                            cmdDisplay.textContent = 'CMD_value: ' + CMD_value;
                        }
                    } else {
                        cmdDisplay.textContent = 'CMD_value header does not exist.';
                    }

                    // Assume server responds with an MP3 file
                    const mp3Blob = await response.blob();
                    const audioPlayer = document.getElementById('audioPlayer');
                    audioPlayer.src = URL.createObjectURL(mp3Blob);
                    audioPlayer.play();
                };

                mediaRecorder.start();
                document.getElementById('recordButton').textContent = 'Stop Recording';
            } else {
                // Stop Recording
                mediaRecorder.stop();
                document.getElementById('recordButton').textContent = 'Start Recording';
            }
        });
    </script>
</body>
</html>
`