<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>ENGI</title>
    <link rel="stylesheet" href="{{ asset('css/app.css') }}">

</head>

<body>


    <div id="container" class="container mt-3">
        <video id="screenVideo" width="1" height="1"></video>
        @can('update', App\Models\Call::class)
            <button class="btn btn-outline-primary" id="startButton">Commencer l'enregistrement</button>
            <button class="btn btn-outline-primary" id="stopButton" disabled>Arrêter l'enregistrement</button>
            <button class="btn btn-success" id="downloadButton" disabled>Enregistrer la Video</button>
            <button type="button" id="capture" class="btn btn-warning">Capture Ecran</button>
            
            @can('screen', App\Models\Call::class)
                {{-- <div class="row">

                <div class="col-6"> --}}
                {{-- <form method="POST" enctype="multipart/form-data" action="{{ route('call.screen', $dossier_id) }}"
                        id="myForm">
                        @csrf</form> --}}
                <input type="hidden" name="img" id="img_val" value="" />
                <!--<button style="" id="btn" class="btn btn-danger mr-2">Leave Call</button>-->

                {{-- </div>
            </div> --}}
            @endcan
        @endcan
        <input id="file" type="hidden" name="video">
        <div class="recorded-video-wrap">
            <video style="display: none" id="video" controls></video>
            <video style="display: none" src="" id="recorded-video" controls></video>
        </div>

    <div class="row mt-2">
        <div class="mb-3 ">
            <iframe  style="width: 98%;height:720px;margin-left:1%" src="{{ $responseData['roomUrl'] }}"
                allow="camera; microphone; fullscreen; speaker; display-capture; autoplay;"></iframe>
        </div>
    </div>
    <input type="hidden" id="dossier_id" value="{{ $dossier->id }}">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-body">
                    <label for=""> Appel Video Lien :</label>
                    <input class="form-control" readonly id="myInput" value="{{ $responseData['roomUrl'] }}"
                        type="text">
                    <button onclick="myFunction()" class="btn btn-dark mt-2">Copier</button>
                    <a href="https://web.whatsapp.com/" target="_blank" class="btn btn-success mt-2">Whatsapp</a>
                </div>
            </div>
        </div>
    </div>
    </div>

    <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>
        const screenVideoElement = document.getElementById('screenVideo');
        const startButton = document.getElementById('startButton');
        const stopButton = document.getElementById('stopButton');
        const downloadButton = document.getElementById('downloadButton');
        let mediaRecorder;
        let recordedChunks = [];
        const dossier_id = document.getElementById('dossier_id').value;
        recordedVideo = document.querySelector('#recorded-video');

        function myFunction() {
            // Get the text field
            var copyText = document.getElementById("myInput");
            // Select the text field
            copyText.select();
            copyText.setSelectionRange(0, 99999); // For mobile devices
            // Copy the text inside the text field
            navigator.clipboard.writeText(copyText.value);
            // Alert the copied text
            alert("Copied");
        }
        async function startRecording() {
            try {
                const stream = await navigator.mediaDevices.getDisplayMedia({
                    video: true,
                    audio: true
                });
                screenVideoElement.srcObject = stream;
                mediaRecorder = new MediaRecorder(stream);

                mediaRecorder.ondataavailable = (event) => {
                    if (event.data.size > 0) {
                        recordedChunks.push(event.data);
                    }
                };

                mediaRecorder.onstop = () => {
                    downloadButton.disabled = false;
                };

                mediaRecorder.start();
                startButton.disabled = true;
                stopButton.disabled = false;
            } catch (error) {
                console.error('Error starting recording: ', error);
            }
        }

        function stopRecording() {
            if (mediaRecorder && mediaRecorder.state === 'recording') {
                mediaRecorder.stop();
                startButton.disabled = false;
                stopButton.disabled = true;

            }
        }

        function downloadVideo() {
            const blob = new Blob(recordedChunks, {
                'type': 'video/mp4'
            });
            recordedVideo.src = URL.createObjectURL(blob);
            recordedVideo.load();
            const formData = new FormData();

            formData.append('video', blob);
            fetch('https://engi.ameamaroc.ma/Call/store/' + dossier_id, {
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    body: formData
                })
                .then(response => {
                    alert('Video Enregistrer');
                    console.log(response);
                })
                .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();
            }

            // Ensure stream is accessible
            const stream = screenVideoElement.srcObject;
            if (stream) {
                // Get tracks and stop them
                const tracks = stream.getTracks();
                tracks.forEach(track => track.stop());
            }

        }
        var items = [];
        $('#capture').click(function() {
            const screenshotTarget = document.getElementById('container');
            html2canvas(screenshotTarget).then(canvas => {
                var item = canvas.toDataURL("image/png", 1);
                const formData = new FormData();
                formData.append('img', item);
                fetch('https://engi.ameamaroc.ma/picture/' + dossier_id, {
                        method: 'POST',
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        body: formData
                    })
                    .then(response => {
                        alert('Capture Ecran Enregistrer');
                        console.log(response);
                    })
                    .catch(error => {
                        console.log(error);
                    });
            });
        });
        $('#btn').click(function() {
            document.getElementById("myForm").submit();
            disconnect();
        });


        startButton.addEventListener('click', startRecording);
        stopButton.addEventListener('click', stopRecording);
        downloadButton.addEventListener('click', downloadVideo);
    </script>
</body>

</html>
