<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>AMEA </title>

    <link rel="stylesheet" href="css/app.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
    <script src="https://static.opentok.com/v2/js/opentok.min.js"></script>
    <style>
        body {
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            background-color: #f8f9fa;
        }

        #videos-container {
            position: relative;
            width: 720px;
            /* Adjust width as needed */
            height: 480px;
            /* Adjust height as needed */
            border: 1px solid #ccc;
            /* Add a border for better visibility */
            border-radius: 5px;
            /* Add some border radius for a softer look */
            overflow: hidden;
            /* Ensure videos don't overflow the container */
        }

        #subscriber {
            position: absolute;
            top: 0;
            left: 0;
            width: 70%;
            /* Adjust width as needed */
            height: 100%;
            border-right: 2px solid #fff;
            /* Add border to separate subscriber from publisher */
        }

        #publisher {
            position: absolute;
            top: 1px;
            /* Adjust as needed */
            left: 70%;
            /* Adjust as needed */
            width: 30%;
            /* Adjust width as needed */
            height: 40%;
            border: 2px solid #fff;
            /* Add border to differentiate */
        }

        .controls {
            position: absolute;
            top: 650px;
            /* Adjust as needed */
            left: 70%;
            /* Adjust as needed */
            width: 30%;
            /* Adjust width as needed */
            height: 30%;
            border: 2px solid #fff;
            /* Add border to differentiate */
        }
    </style>

</head>

<body>
    <div id="videos">
        <div id="subscriber"></div>
        <div id="publisher"></div>
        <div class="controls">
            <label for="audio-source-select">Audio Source:</label>
            <select class="" id="audio-source-select"></select>
            <br>
            <label for="video-source-select">Video Source:</label>
            <select class="" id="video-source-select"></select>
            <br>
            <hr>
            <button class="btn btn-outline-dark" id="cycle-video-btn" type="button">Cycle Video</button>
            <button class="btn btn-outline-dark" id="publish-btn" type="button">Publish</button>
            {{-- <button id="capture" class="btn btn-danger mr-2">Capture</button> --}}
            <br>
            <button class="btn btn-success mt-2" id="screenshot-btn" type="button">Take Screenshot</button>
            <br>
            <input type="hidden" name="" id="dossier_id" value="{{ $dossier_id }}">

            @auth
            @if (Auth::user()->role_id == 4)

            <br>
            <input id="file" type="hidden" name="video">
            <button class="btn btn-primary" id="btnStart">START RECORDING</button>
            <button class="btn btn-warning" id="btnStop">STOP RECORDING</button></p>
            <br>
            <form method="POST" enctype="multipart/form-data" action="{{ route('call.screen', $dossier_id) }}"
                id="myForm">
                @csrf
                <input type="hidden" name="img" id="img_val" value="" />
                <button id="btn" class="btn btn-danger mr-2 mt-1">Leave Call</button>
            </form>
            <div class="recorded-video-wrap">
                <video style="display: none" id="video" controls></video>
                <video style="display: none" src="" id="recorded-video" controls></video>
            </div>
            @endif
            @endauth

        </div>
    </div>

    <!--<label for="audio-source-select">Audio Source:</label>-->
    <!--<select id="audio-source-select"></select><br />-->
    <!--    <div id="audio-meter"><label for="audio-meter">Audio Level:</label><meter min="0" max="1"></meter>-->
    <!--    </div>-->
    <!--    <label for="video-source-select">Video Source:</label>-->
    <!--    <select id="video-source-select"></select>-->
    <!--    <button id="cycle-video-btn" type="button">Cycle Video</button><br />-->
    <!--    <button id="publish-btn" type="button">Publish</button>-->
    <script src="https://static.opentok.com/v2/js/opentok.min.js"></script>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
    <script type="text/javascript" src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
    <script>
        var dossier_id = document.getElementById('dossier_id').value;


        document.getElementById('screenshot-btn').addEventListener('click', function() {
            var publisher = document.getElementById('subscriber');

            html2canvas(publisher).then(function(canvas) {
                // Convert canvas to base64 encoded PNG image
                var item = canvas.toDataURL("image/png", 1)
                // items.push(item);
                // console.log(items);
                // $('#img_val').val(items);

                const formData = new FormData();

                var csrfToken = $('meta[name="csrf-token"]').attr('content');
                formData.append('_token', csrfToken);
                formData.append('img', item);

                fetch('/picture/' + dossier_id, {
                        method: 'POST',
                        headers: {
                            'X-CSRF-TOKEN': csrfToken // Fix: Correct header name
                        },
                        body: formData
                    })
                    .then(response => {
                        // console.log('upload success');
                        alert('Capture Ecran Enregistré avec Succés')
                    })
                    .catch(error => {
                        console.log('error');
                    });

            });
        });
    </script>
    <script type="text/javascript">
        /* global OT */

        (function closure() {
            const audioSelector = document.querySelector('#audio-source-select');
            const videoSelector = document.querySelector('#video-source-select');
            const publishBtn = document.querySelector('#publish-btn');
            const cycleVideoBtn = document.querySelector('#cycle-video-btn');
            let publisher;

            // Get the list of devices and populate the drop down lists
            function populateDeviceSources(selector, kind) {
                OT.getDevices((err, devices) => {
                    if (err) {
                        alert('getDevices error ' + err.message);
                        return;
                    }
                    let index = 0;
                    selector.innerHTML = devices.reduce((innerHTML, device) => {
                        if (device.kind === kind) {
                            index += 1;
                            return `${innerHTML}<option value="${device.deviceId}">${device.label || device.kind + index}</option>`;
                        }
                        return innerHTML;
                    }, '');
                    publishBtn.disabled = false;
                });
            }
            publishBtn.disabled = true;
            // We request access to Microphones and Cameras so we can get the labels
            OT.getUserMedia().then((stream) => {
                populateDeviceSources(audioSelector, 'audioInput');
                populateDeviceSources(videoSelector, 'videoInput');
                // Stop the tracks so that we stop using this camera and microphone
                // If you don't do this then cycleVideo does not work on some Android devices
                stream.getTracks().forEach(track => track.stop());
            });

            // Start publishing when you click the publish button
            publishBtn.addEventListener('click', () => {
                // Disable the audio and video pickers and hide the publish button
                audioSelector.disabled = true;
                videoSelector.disabled = true;
                publishBtn.style.display = 'none';

                // Start publishing with the selected devices
                publisher = OT.initPublisher('publisher', {
                    audioSource: audioSelector.value,
                    videoSource: videoSelector.value
                }, (err) => {
                    if (err) {
                        alert('Publish error ' + err.message);
                    } else {
                        setupDeviceSwitching();
                        setupAudioLevelMeter();
                    }
                });
            });

            // Allow you to switch to different cameras and microphones using
            // setAudioSource and cycleVideo
            function setupDeviceSwitching() {
                audioSelector.disabled = false;

                // When the audio selector changes we update the audio source
                audioSelector.addEventListener('change', (event) => {
                    audioSelector.disabled = true;
                    publisher.setAudioSource(event.target.value).then(() => {
                        audioSelector.disabled = false;
                    }).catch((err) => {
                        alert(`setAudioSource failed: ${err.message}`);
                        audioSelector.disabled = false;
                    });
                });

                // When the cycleVideo button is clicked we call cycleVideo
                cycleVideoBtn.addEventListener('click', () => {
                    cycleVideoBtn.disabled = true;
                    publisher.cycleVideo().then(({
                        deviceId
                    }) => {
                        videoSelector.value = deviceId;
                        cycleVideoBtn.disabled = false;
                    }).catch((err) => {
                        alert('cycleVideo error ' + err.message);
                        cycleVideoBtn.disabled = false;
                    });
                });
                cycleVideoBtn.style.display = 'inline-block';
            }

            function setupAudioLevelMeter() {
                const audioLevel = document.querySelector('#audio-meter');
                const meter = document.querySelector('#audio-meter meter');
                audioLevel.style.display = 'block';
                let movingAvg = null;
                publisher.on('audioLevelUpdated', (event) => {
                    if (movingAvg === null || movingAvg <= event.audioLevel) {
                        movingAvg = event.audioLevel;
                    } else {
                        movingAvg = 0.7 * movingAvg + 0.3 * event.audioLevel;
                    }

                    // 1.5 scaling to map the -30 - 0 dBm range to [0,1]
                    let logLevel = (Math.log(movingAvg) / Math.LN10) / 1.5 + 1;
                    logLevel = Math.min(Math.max(logLevel, 0), 1);
                    meter.value = logLevel;
                });
            }
        })();
    </script>
    <script type="text/javascript">
        var session;
        var connectionCount = 0;
        var apiKey = "{{ env('VONAGE_API_KEY') }}";
        var sessionId = "{{ $sessionId }}";
        var token = "{{ $token }}";
        var publisher;

        function connect() {

            // Replace apiKey and sessionId with your own values:

            session = OT.initSession(apiKey, sessionId);
            session.on("streamCreated", function(event) {
                console.log("New stream in the session: " + event.stream.streamId);
                session.subscribe(event.stream, 'subscriber', {
                    insertMode: 'append',
                    width: '100%',
                    height: '100%'
                });
            });

            session.on({
                connectionCreated: function(event) {
                    connectionCount++;
                    // alert(connectionCount + ' connections.');
                },
                connectionDestroyed: function(event) {
                    connectionCount--;
                    // alert(connectionCount + ' connections.');
                },
                sessionDisconnected: function sessionDisconnectHandler(event) {
                    // The event is defined by the SessionDisconnectEvent class
                    alert('Disconnected from the session.');
                    document.getElementById('disconnectBtn').style.display = 'none';
                    if (event.reason == 'networkDisconnected') {
                        alert('Your network connection terminated.')
                    }
                }
            });

            publisher = OT.initPublisher('publisher', {
                insertMode: 'append',
                width: '100%',
                height: '100%'
            }, error => {
                if (error) {
                    alert(error.message);
                }
            });


            // Replace token with your own value:
            session.connect(token, function(error) {
                if (error) {
                    alert('Unable to connect: ', error.message);
                } else {
                    // document.getElementById('disconnectBtn').style.display = 'block';
                    // alert('Connected to the session.');
                    connectionCount = 1;

                    if (session.capabilities.publish == 1) {
                        session.publish(publisher, function(error) {
                            if (error) {
                                console.error('Error publishing publisher:', error);
                            } else {
                                publisher.cycleVideo().then(function() {
                                    console.log('Video cycled successfully');
                                }).catch(function(error) {
                                    console.error('Error cycling video:', error);
                                });
                            }
                        });
                    } else {
                        alert("You cannot publish an audio-video stream.");
                    }
                }
            });


        }
        connect();
    </script>
    <script>
        let stream = null,
            audio = null,
            mixedStream = null,
            chunks = [],
            recorder = null
        startButton = null,
            stopButton = null,
            downloadButton = null,
            input = null,
            recordedVideo = null;

        async function setupStream() {
            try {
                stream = await navigator.mediaDevices.getDisplayMedia({
                    video: true,
                    audio: true
                });

                audio = await navigator.mediaDevices.getUserMedia({
                    audio: {
                        echoCancellation: true,
                        noiseSuppression: true,
                        sampleRate: 44100,
                    },
                });

                setupVideoFeedback();
            } catch (err) {
                console.error(err)
            }
        }

        function setupVideoFeedback() {
            if (stream) {
                const video = document.querySelector('#video');

                video.srcObject = stream;
                video.play();
            } else {
                console.warn('No stream available');
            }
        }



        async function startRecording() {
            await setupStream();

            if (stream && audio) {
                mixedStream = new MediaStream([...stream.getTracks(), ...audio.getTracks()]);
                recorder = new MediaRecorder(mixedStream);
                recorder.ondataavailable = handleDataAvailable;
                recorder.onstop = handleStop;
                recorder.start(1000);

                startButton.disabled = true;
                stopButton.disabled = false;

                console.log('Recording started');
            } else {
                console.warn('No stream available.');
            }
        }

        function stopRecording() {
            recorder.stop();

            startButton.disabled = false;
            stopButton.disabled = true;
        }

        function handleDataAvailable(e) {
            chunks.push(e.data);
        }

        // function handleStop(e) {
        //     const blob = new Blob(chunks, {
        //         'type': 'video/mp4'
        //     });
        //     chunks = [];
        //     // console.log(recordedVideo.src);

        //     recordedVideo.src = URL.createObjectURL(blob);
        //     recordedVideo.load();
        //     const formData = new FormData();

        //     var csrfToken = $('meta[name="csrf-token"]').attr('content');
        //     formData.append('_token', csrfToken);
        //     formData.append('video', blob);
        //     fetch('/Call/store/' + dossier_id, {

        //             method: 'POST',
        //             headers: {
        //                 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        //             },
        //             body: formData
        //         })
        //         .then(response => {
        //             console.log('upload success');
        //         })
        //         .catch(error => {
        //             console.log('error');
        //         });
        //     recordedVideo.onloadeddata = function() {
        //         const rc = document.querySelector(".recorded-video-wrap");
        //         rc.classList.remove("hidden");
        //         rc.scrollIntoView({
        //             behavior: "smooth",
        //             block: "start"
        //         });
        //         recordedVideo.play();
        //     }

        //     stream.getTracks().forEach((track) => track.stop());
        //     audio.getTracks().forEach((track) => track.stop());

        //     console.log('Recording stopped');
        // }

        function handleStop(e) {
            
            const blob = new Blob(chunks, {
                'type': 'video/mp4'
            });
            chunks = [];

            recordedVideo.src = URL.createObjectURL(blob);
            recordedVideo.load();
            const formData = new FormData();

            var csrfToken = $('meta[name="csrf-token"]').attr('content');
            console.log(csrfToken);
            formData.append('_token', csrfToken);
            formData.append('video', blob);

            fetch('/Call/store/' + dossier_id, {
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': csrfToken // Fix: Correct header name
                    },
                    body: formData
                })
                .then(response => {
                    console.log('upload success');
                })
                .catch(error => {
                    console.log('error');
                });

            recordedVideo.onloadeddata = function() {
                const rc = document.querySelector(".recorded-video-wrap");
                rc.classList.remove("hidden");
                rc.scrollIntoView({
                    behavior: "smooth",
                    block: "start"
                });
                recordedVideo.play();
            }

            stream.getTracks().forEach((track) => track.stop());
            audio.getTracks().forEach((track) => track.stop());

            console.log('Recording stopped');
        }


        window.addEventListener('load', () => {
            startButton = document.querySelector('#btnStart');
            stopButton = document.querySelector('#btnStop');
            input = document.querySelector('#file');
            recordedVideo = document.querySelector('#recorded-video');

            startButton.addEventListener('click', startRecording);
            stopButton.addEventListener('click', stopRecording);
        })
    </script>
    <script type="text/javascript">
        $('#btn').click(function() {
            document.getElementById("myForm").submit();
            disconnect();
        });
    </script>
</body>

</html>
