<?php
    require_once('.htac_header.php');
?>
<div class="diZMaxW600 diZmxAuto diZFlexColumn diZmb20">
    <h1 class="diZTextCenter diZBorderBottom">Screen Recorder</h1>
    <div class="diZFlexRow ">
        <button class="diZSpaceR" id="start"><span>Start Recording</span></button>
        <button class="diZSpaceR" id="stop" disabled><span>Stop Recording</span></button>
        <button class="diZSpaceR" id="download" disabled><span>Download Recording</span></button>
    </div>
    <div class="diZTextCenter diZmb4 diZmt4" id="timer">Duration: 00:00:00</div>
    <video class="diZw100" id="video" muted controls autoplay></video>
</div>
<script>
    const startButton = document.getElementById('start');
    const stopButton = document.getElementById('stop');
    const downloadButton = document.getElementById('download');
    const video = document.getElementById('video');
    const timer = document.getElementById('timer');

    let mediaRecorder;
    let recordedChunks = [];
    let startTime;
    let timerInterval;

    function formatTime(time) {
        const hours = String(Math.floor(time / 3600)).padStart(2, '0');
        const minutes = String(Math.floor((time % 3600) / 60)).padStart(2, '0');
        const seconds = String(time % 60).padStart(2, '0');
        return `${hours}:${minutes}:${seconds}`;
    }

    function startTimer() {
        startTime = Date.now();
        timerInterval = setInterval(() => {
            const elapsedTime = Math.floor((Date.now() - startTime) / 1000);
            timer.textContent ='Duration: ' + formatTime(elapsedTime);
        }, 1000);
    }

    function stopTimer() {
        clearInterval(timerInterval);
    }

    startButton.addEventListener('click', async () => {
        if (!navigator.mediaDevices || !navigator.mediaDevices.getDisplayMedia) {
            console.log('getDisplayMedia is not supported in your browser.');
            return;
        }

        try {
            const stream = await navigator.mediaDevices.getDisplayMedia({
                video: { mediaSource: 'screen' },
                audio: true // Enable audio recording
            });

            // Show live video feed in the video element
            video.srcObject = stream;

            mediaRecorder = new MediaRecorder(stream);

            mediaRecorder.ondataavailable = (event) => {
                if (event.data.size > 0) {
                    console.log('Data available:', event.data.size);
                    recordedChunks.push(event.data);
                }
            };

            mediaRecorder.onstop = () => {
                console.log('Recording stopped. Creating blob.');
                if (recordedChunks.length > 0) {
                    const blob = new Blob(recordedChunks, {
                        type: 'video/webm'
                    });
                    const url = URL.createObjectURL(blob);
                    video.src = url;
                    downloadButton.href = url;
                    downloadButton.download = 'recording.webm';
                    downloadButton.disabled = false;
                } else {
                    console.error('No recorded data available.');
                }
            };

            mediaRecorder.start();
            startTimer();

            startButton.disabled = true;
            stopButton.disabled = false;
            downloadButton.disabled = true;
        } catch (error) {
            console.error('Error: ' + error);
        }
    });

    stopButton.addEventListener('click', () => {
        if (mediaRecorder && mediaRecorder.state !== 'inactive') {
            mediaRecorder.stop();
            stopTimer();

            startButton.disabled = false;
            stopButton.disabled = true;
        } else {
            console.error('No active recording to stop.');
        }
    });

    downloadButton.addEventListener('click', () => {
        if (recordedChunks.length > 0) {
            const blob = new Blob(recordedChunks, {
                type: 'video/webm'
            });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.style.display = 'none';
            a.href = url;
            a.download = 'recording.webm';
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(url);
            recordedChunks = [];
        } else {
            console.error('No data available for download.');
        }
    });
</script>