<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Webcam Recorder</title>
</head>
<body>
    <video id="video" width="640" height="480" autoplay></video>
    <button id="startRecord">Start Recording</button>
    <button id="stopRecord">Stop Recording</button>
    <button id="save">Save</button>
    <canvas id="canvas" style="display: none;"></canvas>

    <script>
        let video = document.getElementById('video');
        let startRecordBtn = document.getElementById('startRecord');
        let stopRecordBtn = document.getElementById('stopRecord');
        let saveBtn = document.getElementById('save');
        let canvas = document.getElementById('canvas');
        let ctx = canvas.getContext('2d');
        let stream;

        navigator.mediaDevices.getUserMedia({ video: true })
            .then(function (mediaStream) {
                video.srcObject = mediaStream;
                stream = mediaStream;
            })
            .catch(function (err) {
                console.error('Could not access the webcam: ', err);
            });

        startRecordBtn.onclick = function () {
            console.log('Recording testprint')
            stream.getVideoTracks()[0].requestRecord({ mimeType: 'video/webm' })
                .then(() => console.log('Recording started'))
                .catch(err => console.error('Failed to start recording: ', err));
        };

        stopRecordBtn.onclick = function () {
            stream.getVideoTracks()[0].stopRecord()
                .then(blob => {
                    console.log('Recording stopped');
                    let videoURL = URL.createObjectURL(blob);
                    video.src = videoURL;
                })
                .catch(err => console.error('Failed to stop recording: ', err));
        };

        saveBtn.onclick = function () {
            let data = video.toDataURL('image/png');
            fetch('/send_video', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ image: data })
            })
            .then(response => response.json())
            .then(data => console.log('Video saved successfully:', data))
            .catch(error => console.error('Error saving video:', error));
        };
    </script>
</body>
</html>