<?php $__env->startSection('content'); ?>
    <link href="https://vjs.zencdn.net/7.11.4/video-js.css" rel="stylesheet" />
    <script src="https://vjs.zencdn.net/7.11.4/video.min.js"></script>

    <style>
        video {
            max-width: 100%;
            height: auto;
        }

        .glowing-text {
            color: #000;
            /* Base text color (adjust as needed) */
            font-weight: bold;
            animation: fade 1s infinite alternate;
        }

        @keyframes fade {
            0% {
                opacity: 1;
            }

            50% {
                opacity: 0.5;
            }

            100% {
                opacity: 1;
            }
        }
    </style>
    
    <div class="container-xxl flex-grow-1 container-p-y">

        <div class="card">
            <h5 class="card-header card-title">Add New Camera</h5>
            <div class="table-responsive text-nowrap">
                <form action="<?php echo e(route('streamWithCamera.save')); ?>" method="POST">
                    <?php echo csrf_field(); ?>

                    <div id="step_1">
                        <?php echo $__env->make('add.partials.add_camera', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
                    </div>
                    <div id="step_2" class="d-none">
                        <?php echo $__env->make('add.partials.add_region', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>

                    </div>


                    <div class="row" style="margin: 50px; display: block; text-align: center;">
                        <button type="button" class="btn btn-default" style="width:150px;"
                            id="previous_btn">Previous</button>
                        <button type="button" class="btn btn-default" style="width:150px;" id="next_btn">Next</button>
                    </div>

                    <div class="row d-none" style="margin: 50px;display: block;text-align: center;;">
                        <input style="width:150px;" type="submit" value="Submit" class="btn btn-secondary"
                            id="sbmt_btn" />
                    </div>
                </form>
            </div>
            <div class="row" style="margin:10px; margin-top: -30px">
                <h5>Sample Camera Sources</h5>
                <a href="https://video.codxcanvas.com/people.mp4">https://video.codxcanvas.com/people.mp4</a><br>
                <a href="https://video.codxcanvas.com/sample1.mp4">https://video.codxcanvas.com/sample1.mp4</a><br>
                <a href="https://video.codxcanvas.com/sample1.mp4">https://video.codxcanvas.com/sample1.mp4</a><br>
                <a href="http://142.0.109.159/axis-cgi/mjpg/video.cgi">http://142.0.109.159/axis-cgi/mjpg/video.cgi</a><br>
                <a
                    href="http://dash.akamaized.net/dash264/TestCases/2b/qualcomm/2/MultiRes.mpd">http://dash.akamaized.net/dash264/TestCases/2b/qualcomm/2/MultiRes.mpd</a><br>

                
            </div>
        </div>

        <link href="https://vjs.zencdn.net/7.11.4/video-js.css" rel="stylesheet" />
        <script src="https://vjs.zencdn.net/7.11.4/video.min.js"></script>


        <script>
            document.addEventListener('DOMContentLoaded', function() {
                const step1 = document.getElementById('step_1');
                const step2 = document.getElementById('step_2');
                const nextBtn = document.getElementById('next_btn');
                const prevBtn = document.getElementById('previous_btn');
                const submitBtn = document.getElementById('sbmt_btn');
                const verifyBtn = document.getElementById('verify_btn');
                const streamUrlInput = document.getElementById('stream_url');
                const showUrlMsg = document.getElementById('show_url_msg');

                // Initially hide previous and next buttons, disable verify button
                prevBtn.style.display = 'none';
                nextBtn.style.display = 'none';
                submitBtn.parentElement.classList.add('d-none');
                verifyBtn.disabled = true; // Disable verify button by default

                // Function to show message in the show_url_msg div
                function showMessage(msg, color) {
                    showUrlMsg.textContent = msg;
                    showUrlMsg.style.color = color;
                }

                // Function to handle enabling/disabling the verify button based on input value
                function toggleVerifyBtn() {
                    if (streamUrlInput.value.trim() === '') {
                        verifyBtn.disabled = true;
                        document.getElementById('showStreamContent').innerHTML =
                            ''; // remove video player and stream info
                        showMessage('Please enter a URL to verify.', 'yellow');
                    } else {
                        verifyBtn.disabled = false; // Enable verify button when URL is present
                        document.getElementById('showStreamContent').innerHTML =
                            ''; // remove video player and stream info
                        showMessage('', ''); // Clear message when URL is present
                    }
                }

                // Function to hide all navigation buttons and submit button
                function hideNavigationButtons() {
                    nextBtn.style.display = 'none';
                    prevBtn.style.display = 'none';
                    submitBtn.parentElement.classList.add('d-none'); // Hide submit button
                }

                // Check the URL input on every input event
                streamUrlInput.addEventListener('input', function() {
                    toggleVerifyBtn();

                    // Show verify button and hide next/prev buttons when URL changes
                    if (verifyBtn.disabled) {
                        hideNavigationButtons();
                    } else {
                        verifyBtn.style.display = 'inline-block';
                        hideNavigationButtons();
                    }
                });

                // Call this function when input is loaded to set the initial state of the verify button
                toggleVerifyBtn();

                // Verify button click handler
                verifyBtn.addEventListener('click', function() {
                    if (!verifyBtn.disabled) {
                        // Call the stream metadata verification function
                        getStreamMetadata();
                        showMessage('Validating...', 'Yellow'); // Clear message when URL is present
                    }
                });

                // Simulating URL verification process with getStreamMetadata
                function getStreamMetadata() {
                    const videoUrl = streamUrlInput.value;

                    fetch(`<?php echo e(url('/get-stream-metadata')); ?>?stream_url=${encodeURIComponent(videoUrl)}`)
                        .then(response => response.json())


                        .then(data => {
                            console.log(data)
                            const videoStream = data.data.streams.find(stream => stream.codec_type === 'video');

                            if (videoStream) {
                                document.getElementById('video_type_inpt').value = data.video_type
                                if (data.video_type == 'normal') {

                                    // Get the media URL from the server-side variable
                                    var mediaUrl = videoUrl;
                                    // Example mediaUrl: "http://142.0.109.159/axis-cgi/mjpg/video.cgi"

                                    // Define the video formats and their corresponding MIME types
                                    const allVideoFormat = {
                                        'mpd': "application/dash+xml",
                                        'mp4': "video/mp4",
                                        'webm': "video/webm",
                                        'ogg': "video/ogg",
                                        'm3u8': "application/x-mpegURL",
                                        'mjpeg': "video/x-motion-jpeg",
                                        'avi': "video/x-msvideo",
                                        'mov': "video/quicktime",
                                        'mkv': "video/x-matroska",
                                        '3gp': "video/3gpp",
                                        '3g2': "video/3gpp2",
                                        'asf': "video/x-ms-asf",
                                        'flv': "video/x-flv",
                                        'f4v': "video/x-f4v",
                                        'ts': "video/mp2t",
                                        'mpeg': "video/mpeg",
                                        'mpg': "video/mpeg",
                                        'wmv': "video/x-ms-wmv",
                                        'divx': "video/divx",
                                        'xvid': "video/xvid",
                                        'vob': "video/dvd",
                                        'mts': "video/avchd",
                                        'm2ts': "video/avchd",
                                        'hevc': "video/hevc",
                                        'h264': "video/h264",
                                        'h265': "video/h265",
                                        'dv': "video/x-dv",
                                        'rm': "application/vnd.rn-realmedia",
                                        'rv': "video/vnd.rn-realvideo",
                                        'drc': "video/x-dirac"
                                    };

                                    // Define the image formats and their MIME types
                                    const allImageFormat = {
                                        'jpg': "image/jpeg",
                                        'jpeg': "image/jpeg",
                                        'png': "image/png",
                                        'gif': "image/gif",
                                        'bmp': "image/bmp",
                                        'webp': "image/webp",
                                        'svg': "image/svg+xml"
                                    };

                                    // Extract the file extension from the URL
                                    var fileExtension = mediaUrl.split('.').pop().split(/\#|\?/)[0].toLowerCase();

                                    // Determine whether the URL is for a video or an image
                                    var mediaHTML = '';

                                    if (fileExtension === 'cgi' || fileExtension === 'mjpg' || fileExtension ===
                                        'mjpeg') {
                                        // URL is an MJPEG stream
                                        mediaHTML = `
                                 <img src="${mediaUrl}" alt="MJPEG Stream" width="300" />
                                     `;
                                    } else if (allVideoFormat[fileExtension]) {
                                        // URL is a video
                                        var mimeType = allVideoFormat[fileExtension];
                                        mediaHTML = `
                                <video id="my-video" class="video-js vjs-default-skin" controls preload="auto"
                                    width="300" height="170" data-setup='{}'>
                                    <source src="${mediaUrl}" type="${mimeType}" />
                                    <!-- Fallback -->
                                    <p>Your browser does not support the video tag.</p>
                                </video>
                                    `;
                                    } else if (allImageFormat[fileExtension]) {
                                        // URL is an image
                                        var mimeType = allImageFormat[fileExtension];
                                        mediaHTML = `
                                     <img src="${mediaUrl}" alt="Media Image" width="640" />
                                        `;
                                    } else {
                                        // Unknown format
                                        mediaHTML = `<p>Unsupported media format.</p>`;
                                    }
                                    const format_name = `${data.data.format.format_name}`.split(',');
                                    const firstFormat = format_name[0];

                                    let bitRate = videoStream.bit_rate; // 1887207 bps

                                    // Convert to Kbps (kilobits per second)
                                    let bitRateKbps = (bitRate / 1000).toFixed(2) + ' (bps)';

                                    // Convert to Mbps (megabits per second)
                                    let bitRateMbps = (bitRate / 1000000).toFixed(2) + ' Mbps';

                                    const content = `
                                <div class="row d-flex justify-content-center">
                                    <div class="col-md-4 d-flex align-items-center">
                                     <ul>
                                         <li> <i class="bi bi-check-circle-fill"></i>  Stream Format: ${firstFormat} </li>
                                         <li> <i class="bi bi-check-circle-fill"></i>  Codec: ${videoStream.codec_name} </li>
                                         <li> <i class="bi bi-check-circle-fill"></i>  Bit Rate: ${bitRateKbps} </li>
                                       </ul>
                                 </div>
                                 <div class="col-md-4 ">
                                        ${mediaHTML}
                                 </div>
                                </div>
                                `;

                                    document.getElementById('showStreamContent').innerHTML = content;

                                    // Initialize Video.js after the video element is added to the DOM
                                    if (allVideoFormat[fileExtension]) {
                                        videojs(document.getElementById('my-video'));
                                    }



                                    // Assuming the verification is successful, show the next and previous buttons
                                    showButtons('next'); // Show the "Next" button and hide the "Previous" button
                                    verifyBtn.style.display = 'none'; // Hide verify button after success
                                    submitBtn.parentElement.classList.add('d-none'); // Hide submit button
                                    showMessage('URL validate successfully! Video stream detected.',
                                        'lightgreen'); // Green success message
                                } else {
                                    // Assuming the video URL is a YouTube link
                                    var mediaUrl = videoUrl;

                                    // Extract the YouTube video ID from the URL
                                    var videoId = mediaUrl.split('v=')[1];
                                    var ampersandPosition = videoId.indexOf('&');
                                    if (ampersandPosition != -1) {
                                        videoId = videoId.substring(0, ampersandPosition);
                                    }

                                    // Create the YouTube embed URL
                                    var youtubeEmbedUrl = `https://www.youtube.com/embed/${videoId}`;

                                    // Generate the HTML for the YouTube player with the specified size
                                    var mediaHTML = `
    <iframe width="300" height="170" src="${youtubeEmbedUrl}" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
`;

                                    const content = `
    <div class="row d-flex justify-content-center">
        <div class="col-md-4 d-flex align-items-center">
            <ul>
                <li> <i class="bi bi-check-circle-fill"></i>  Stream Format: ${videoStream.codec_type} </li>
                <li> <i class="bi bi-check-circle-fill"></i>  Codec: ${videoStream.codec_name} </li>
                <li> <i class="bi bi-check-circle-fill"></i>  Bit Rate: ${videoStream.bit_rate} </li>
            </ul>
        </div>
        <div class="col-md-4 ">
            ${mediaHTML}
        </div>
    </div>
`;

                                    document.getElementById('showStreamContent').innerHTML = content;

                                    // Assuming the verification is successful, show the next and previous buttons
                                    showButtons('next'); // Show the "Next" button and hide the "Previous" button
                                    verifyBtn.style.display = 'none'; // Hide verify button after success
                                    submitBtn.parentElement.classList.add('d-none'); // Hide submit button
                                    showMessage('URL validate successfully! YouTube video detected.',
                                        'green'); // Green success message

                                }
                            } else {
                                // No video stream found, show error message
                                showMessage('No video stream found in the URL. Please provide a valid video URL.',
                                    'red');
                            }
                        })
                        .catch(error => {
                            console.error('Error fetching stream metadata:', error);
                            showMessage('Failed to verify URL. Please try again.', 'red'); // Red error message
                        });
                }


                // Function to show "Next" or "Previous" button
                function showButtons(buttonType) {
                    if (buttonType === 'next') {
                        nextBtn.style.display = 'inline-block';
                        prevBtn.style.display = 'none';
                        submitBtn.parentElement.classList.add('d-none'); // Hide submit button
                    } else if (buttonType === 'prev') {
                        nextBtn.style.display = 'none';
                        prevBtn.style.display = 'inline-block';
                        submitBtn.parentElement.classList.add('d-none'); // Hide submit button
                    } else {
                        hideNavigationButtons();
                    }
                }

                // Next button click handler
                nextBtn.addEventListener('click', function() {
                    step1.classList.add('d-none');
                    step2.classList.remove('d-none');
                    showButtons('prev'); // Show the "Previous" button and hide the "Next" button
                    submitBtn.parentElement.classList.remove('d-none'); // Show submit button
                });

                // Previous button click handler
                prevBtn.addEventListener('click', function() {
                    step2.classList.add('d-none');
                    step1.classList.remove('d-none');
                    showButtons('next'); // Show the "Next" button and hide the "Previous" button
                    submitBtn.parentElement.classList.add('d-none'); // Hide submit button
                });
            });

            // ---- handle switch btn ----

            document.addEventListener('DOMContentLoaded', function() {
                const customSwitch = document.querySelector('.custom-switch');

                // Function to toggle classes based on checked state
                function toggleSwitchClass() {
                    if (customSwitch.checked) {
                        customSwitch.classList.add('bg-primary');
                        customSwitch.classList.remove('bg-dark');
                    } else {
                        customSwitch.classList.add('bg-dark');
                        customSwitch.classList.remove('bg-primary');
                    }
                }

                // Add event listener for change event on the switch
                customSwitch.addEventListener('change', toggleSwitchClass);

                // Initial check to apply correct class on load
                toggleSwitchClass();
            });


            // ---- show & hide object count div ----
            // Get references to the checkbox and the div
            const checkbox = document.getElementById('object_count_switch');
            const objectCountDiv = document.getElementById('object_count_div');

            // Function to toggle the visibility of the div
            function toggleDivVisibility() {
                if (checkbox.checked) {
                    objectCountDiv.style.display = 'block'; // Show the div
                } else {
                    objectCountDiv.style.display = 'none'; // Hide the div
                }
            }

            // Add event listener to the checkbox
            checkbox.addEventListener('change', toggleDivVisibility);
        </script>

        <div class="row" style=" text-align: center; display: block; margin-top: 100px; margin-bottom: 65px; ">
        </div>


    </div>
    </div>



    </div>

<?php $__env->startSection('script_section'); ?>
    <script>
        $(document).ready(function() {
            $('#mySelect').select2();
        });
    </script>
<?php $__env->stopSection(); ?>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.master', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH C:\xampp\htdocs\surveillance\resources\views/add/add_camera_and_region.blade.php ENDPATH**/ ?>