const buttonCamera = document.getElementById('buttonCamera');
const buttonRecord = document.getElementById('buttonRecord');
const buttonDelete = document.getElementById('buttonDelete');
const videoDisplay = document.getElementById('videoDisplay');
const buttonCameraIcon = document.getElementById('buttonCameraIcon');
const buttonRecordIcon = document.getElementById('buttonRecordIcon');
const buttonDeleteIcon = document.getElementById('buttonDeleteIcon');
const videoContainer = document.getElementById('videoContainer');
var mediaRecorder = null;
var stream = null;
let recordedVideoBlob = null;
let isRecording = false;
let videoAccess = false;

// Handle form submission
document.getElementById("question_form").addEventListener("submit", function (event) {
    event.preventDefault(); // Prevent the default form submission
    console.log("submit button pressed");
    // Create a FormData object
    const formData = new FormData(event.target);

    console.log("form data: ",formData);

    // Append the recorded video Blob to the FormData object
    if (recordedVideoBlob) {
        console.log("video is available: ", recordedVideoBlob);
        formData.append("recordedVideo", recordedVideoBlob, "recordedVideo.webm");
    }

    
    console.log("Data to be submitted: ",formData);
    
    // Use fetch to send the form data and video to the backend
    console.log("try to send the form and video");
    fetch("/send_json", {
        method: "POST",
        body: formData
    }).then(response => {
        console.log('Response:', response);
        // Check if response is a redirect (HTTP 3xx status)
        if (response.redirected) {
            console.log("Redirecting to:", response.url);
            window.location.href = response.url; // Redirect to the new page
        } else {
            console.log("Non-redirect response received.");
            // Handle other responses if needed
        }
    })
    .catch(error => {
        console.error('Error:', error);
        // Handle errors if fetch fails
    });
});

async function cameraButton() {
    if (!videoAccess) {
        console.log("cameraButton case videoAccess = false");
        try {
            stream = await navigator.mediaDevices.getUserMedia({
                video: true,
            });
        } catch (error) {
            console.log("Error: ", error);
            return;
        }
        console.log("stream is active");
        videoAccess = true;

        videoDisplay.srcObject = stream;

        buttonCameraIcon.src = ICON_PATHS.cameraofficon;
        buttonCameraIcon.alt = "Camera-off Icon";
        buttonRecord.style.display = 'inline-block';
        buttonDelete.style.display = 'inline-block';
        videoDisplay.style.display = 'inline-block';
        videoContainer.style.display = 'inline-block';

        mediaRecorder = new MediaRecorder(stream, {
            mimeType: "video/webm", // could use different video format
            // videoBitsPerSecond: 5000000, // Standard bitrate for video is 2,5 mbps
        });

        mediaRecorder.addEventListener("dataavailable", (event) => {
            console.log("Data available Event triggered");
            if (event.data.size > 0) {
                recordedVideoBlob = event.data;
                console.log("Data available:", recordedVideoBlob);
            } else {
                console.log("No Data available");
            }
        });

        mediaRecorder.addEventListener("stop", () => {
            if (recordedVideoBlob) {
                videoDisplay.srcObject = null;
                videoDisplay.src = URL.createObjectURL(recordedVideoBlob);
                videoDisplay.controls = true;
                videoDisplay.pause();

                buttonRecordIcon.src = ICON_PATHS.recordicon;
                buttonRecordIcon.alt = 'Record Icon';
                isRecording = false;
                console.log('Recording stopped');
                console.log("Src path:", videoDisplay.src);
            }
        });

    } else {
        console.log("cameraButton case videoAccess = true");

        stream.getTracks().forEach(track => track.stop()); // Stop all tracks to release the camera
        stream = null;
        videoAccess = false;

        buttonCameraIcon.src = ICON_PATHS.cameraicon;
        buttonCameraIcon.alt = "Camera Icon";
        buttonRecord.style.display = 'none';
        buttonDelete.style.display = 'none';
        videoDisplay.style.display = 'none';
        videoContainer.style.display = 'none';
    }
    console.log("camera button function ends");
}

function recordButton() {
    console.log("recordButton pressed");
    if (!isRecording) {
        console.log("recordButton pressed case isRecording = false");
        deleteButton();
        buttonDelete.setAttribute("disabled", "");
        buttonDeleteIcon.classList.add("buttondisable");
        videoDisplay.srcObject = stream;
        videoDisplay.src = null;
        videoDisplay.controls = false;
        mediaRecorder.start();
        console.log("video bitrate = ",mediaRecorder.videoBitsPerSecond);

        buttonRecordIcon.src = ICON_PATHS.stopicon;
        buttonRecordIcon.alt = 'Stop Icon';
        isRecording = true;
        console.log('Recording started');
    } else {
        console.log("recordButton pressed case isRecording = true");
        mediaRecorder.stop();

        console.log("recording stops");
        buttonDelete.removeAttribute("disabled");
        buttonDeleteIcon.classList.remove("buttondisable");
    }
}

function deleteButton() {
    // TODO delete data
    videoDisplay.controls = false;
    videoDisplay.srcObject = stream;
    recordedVideoBlob = null
    buttonDelete.setAttribute("disabled", "");
    buttonDeleteIcon.classList.add("buttondisable");
}
