@extends('layouts.master')
@section('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: #ffffff;
            /* Text color */
            text-shadow: 0 0 5px #ffffff, 0 0 10px #ffffff, 0 0 15px #ffffff, 0 0 20px #ffffff;
            animation: blink 1s infinite alternate;
        }

        @keyframes blink {
            0% {
                text-shadow: 0 0 5px #ffffff, 0 0 10px #ffffff, 0 0 15px #ffffff, 0 0 20px #ffffff;
            }

            100% {
                text-shadow: none;
            }
        }

        select option {
            background-color: #007bff !important;
            color: white !important;
        }

        @keyframes blink {
            50% {
                opacity: 0;
            }
        }

        .blinking-element {
            width: 20px;
            height: 20px;
            border-radius: 50%;
            animation: blink 1s infinite;
            background-color: red;
        }
    </style>


    <!-- Modal -->
    <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" data-bs-target="#staticBackdrop"
        aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h1 class="modal-title fs-5" id="exampleModalLabel">Motion Detection Video</h1>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <video id="playVideo" width="100%" height="100%" controls>

                        <source src="" type="video/mp4">



                        Your browser does not support the video tag.

                    </video>
                </div>
            </div>
        </div>
    </div>

    <div class="container-xxl flex-grow-1 container-p-y">


        <div class="card mb-5">
            <h5 class="card-header card-title">Motion Detection</h5>

            <div class="row container">
                <div class="col-md-2 d-flex align-items-center">
                    <h3 class="">Filters:</h3>
                </div>
                <div class="col-md-3 d-flex align-items-center">
                    <input type="text" class="form-control" id="searchCamera" placeholder="Search Camera">
                </div>
                <div class="col-md-3 d-flex align-items-center">
                    <input type="text" class="form-control" id="searchUrl" placeholder="Search Stream URL">
                </div>
            </div>


            <div class="container row">
                {{-- <div class="col-md-4">
                    <label for="">Select Region</label>
                    <select name="" class="form-control" id="selectRegion">
                        <option value="">Select Region</option>
                        @if ($regions)
                            @foreach ($regions as $item)
                                <option value="{{ $item->_id }}">{{ $item->region }}</option>
                            @endforeach
                        @endif
                    </select>

                </div> --}}

                <div class="col-md-4">
                    <label for="">Select Camera</label>
                    <select name="" class="form-control" id="selectCamera">
                        <option value="">Select Camera</option>
                        @if ($cameras)
                            @foreach ($cameras as $item)
                                <option value="{{ $item->_id }}">{{ $item->cameraname }}</option>
                            @endforeach
                        @endif
                    </select>

                </div>

            </div>
            {{-- <div class="blinking-element">
            </div> --}}

            <div class="table-responsive text-nowrap container mt-5 px-3">
                <table class="display table " id="myDataTable" style="height: 100%;">
                    <thead>
                        <tr class="text-nowrap">
                            <th>#</th>
                            <th>Camera Name</th>
                            <th>Region Name</th>
                            <th>Streaming URl</th>
                            <th>Timestamp</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody id="tableBody">

                    </tbody>

                </table>

            </div>

        </div>


    </div>


    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://js.pusher.com/8.2.0/pusher.min.js"></script>

    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>


    <script>
        $(document).ready(function() {
            // Automatically select the last option
            // var $selectRegion = $('#selectRegion');
            // var lastIndex = $selectRegion.find('option').length - 1;
            // $selectRegion.prop('selectedIndex', lastIndex);

            // // Manually call the change handler to send AJAX request for the last option
            // var regionId = $selectRegion.val(); // Get value of the last option
            // if (regionId != "") {
            //     sendAjaxRequest(regionId); // Call function to send AJAX request
            // }

            // // Handle change event
            // $selectRegion.change(function() {
            //     var regionId = $(this).val();
            //     if (regionId != "") {
            //         sendAjaxRequest(regionId); // Call function to send AJAX request
            //     }
            // });


            // Automatically select the last camera


            var $selectCamera = $('#selectCamera');
            var lastIndex = $selectCamera.find('option').length - 1;
            $selectCamera.prop('selectedIndex', lastIndex);

            // Manually call the change handler to send AJAX request for the last option
            var cameraId = $selectCamera.val(); // Get value of the last option
            if (cameraId != "") {
                sendAjaxRequest(cameraId); // Call function to send AJAX request
            }

            // Handle change event
            $selectCamera.change(function() {
                var cameraId = $(this).val();
                if (cameraId != "") {
                    sendAjaxRequest(cameraId); // Call function to send AJAX request
                }
            });

            // Function to handle AJAX request
            function sendAjaxRequest(cameraId) {
                var url = "{{ route('motion_detection_details_camera', ['camera_id' => '__cameraId__']) }}"
                    .replace('__cameraId__', cameraId);
                console.log("url: " + url);

                $.ajax({
                    url: url,
                    method: 'GET',

                    success: function(response) {
                        // myDataTable
                        var tbody = '';
                        // Iterate over all keys in the response
                        for (var key in response) {
                            // Check if the key is a numeric index
                            if (!isNaN(key) && typeof response[key] === 'object') {
                                var camera = response[key];
                                var index = parseInt(key) + 1;


                                // createdAtValue = new Date(parseInt(camera.motion_created_at["$date"][
                                //     "$numberLong"
                                // ])).toISOString();


                                if (camera.motion_created_at && camera.motion_created_at["$date"] &&
                                    camera
                                    .motion_created_at["$date"]["$numberLong"]) {
                                    createdAtValue = new Date(parseInt(camera.motion_created_at["$date"]
                                        [
                                            "$numberLong"
                                        ])).toISOString();
                                } else {
                                    // createdAtValue = new Date().toISOString();
                                    createdAtValue = "";

                                }

                                var viewUrl = `
    <a href="javascript:void()" tabindex="0" class="" role="button" data-bs-toggle="popover" data-bs-trigger="focus" data-bs-title="Stream URL" data-bs-content="${camera['stream_url']}">View URL</a>
`;


                                // Generate table row with camera details
                                tbody += `
                <tr>
                    <td>${index}</td>
                    <td class=''>
                        <div class= "d-flex">

                        ${camera['cameraname']}
                        <div class= "mx-1 " id="camera_${camera['_id']['$oid']}">
                        <div>
                        <div>


                    </td>
                    <td>${camera['region_name']}</td>
                    <td>
${viewUrl}

</td>

                    <td>${createdAtValue}</td>

                    <td>
                        <button type="button" class="btn btn-secondary btn-sm" data-bs-toggle="modal" data-bs-target="#exampleModal" onclick="playVideo('http://slickdriver.com:8084/${camera['motion_detect_path']}')">
                            Play Video
                        </button>
                    </td>
                </tr>
            `;
                            }
                        }

                        // Insert the generated tbody content into the HTML element with id 'tableBody'
                        $('#tableBody').html(tbody);
                    },

                    error: function(xhr, status, error) {
                        console.error('An error occurred:', error);
                    }
                });
            }
        });







        // bootstrap modal

        const myModal = document.getElementById('exampleModal')
        const myInput = document.getElementById('myInput')

        myModal.addEventListener('shown.bs.modal', () => {})

        // Close the modal

        myModal.addEventListener('click', (event) => {

            if (event.target == myModal) {
                playVideo("");
            }

        });

        function playVideo(src) {
            document.getElementById('playVideo').src = src;
        }



        const popoverTriggerList = document.querySelectorAll('[data-bs-toggle="popover"]')
        const popoverList = [...popoverTriggerList].map(popoverTriggerEl => new bootstrap.Popover(popoverTriggerEl))

        // ~ filter ~


        $(document).ready(function() {



            $("#searchCamera").on('keyup', function() {
                $('#myDataTable').DataTable().column(1).search(
                    $(this).val(),
                    false, // regex
                    true // smart search
                ).draw();
            });
            $("#searchUrl").on('keyup', function() {
                $('#myDataTable').DataTable().column(3).search(
                    $(this).val(),
                    false, // regex
                    true // smart search
                ).draw();
            });

        })





        // Enable pusher logging - don't include this in production
        Pusher.logToConsole = true;
        var pusher = new Pusher(
            '{{ env('PUSHER_APP_KEY') }}', {
                cluster: '{{ env('PUSHER_APP_CLUSTER') }}'
            });

        var channel = pusher.subscribe('my-channel');

        channel.bind('my-event', function(data) {
            // var msgg = data['message'];
            console.log(data.message);
            var _data = data.message

            cam_id = document.getElementById('cust_alarm_cam_id').value;

            // if (cam_id == _data.camera_id) { // show only currnet camera notification
            if (_data.type == "motion_detection") {

                // Assuming _data is your object containing the camera_id
                let cameraId = _data.camera_id;

                // Construct the id selector using the camera id
                let divId = 'camera_' + cameraId;

                // Find the div element by the constructed id
                let divElement = document.getElementById(divId);

                // Check if the div element exists
                if (divElement) {
                    // Add the 'blinking_element' class to the div
                    divElement.classList.add('blinking_element');
                } else {
                    console.log('Element with id ' + divId + ' not found.');
                }

                // incrementCounter('motion_detection_count')
            }
            // }

        });
    </script>

@endSection
