@extends('layouts.app')

@section('style')
    <link href="https://cdnjs.cloudflare.com/ajax/libs/video.js/7.10.2/video-js.min.css" rel="stylesheet">

    <link href="https://unpkg.com/@videojs/themes@1.0.1/dist/sea/index.css" rel="stylesheet" />

    <style>
        video{
            background: #f2f2f2;
            border: 1px solid #000000;
        }

        .vjs-logo-content{
            z-index: 99999;
            position: relative;
        }

     @media screen and (min-width: 320px) and (max-width: 767px){
        .my-video-dimensions{width:100%; margin-left: 0px !important;}
        video#record_user { width: 100%;}
        .p-2 { padding: 0px !important;}
        div#video {padding: 0px;}
     }

    .video-js {
		background:none;
		border: 14px solid #8f24f9;
	}
    </style>

@endsection


@section('contect')
    @if(!empty($videoinfo))

        <style>
            /*.vi_pq {*/
            /*    width: 100%;*/
            /*    height: 382px;*/
            /*    border-radius: 20px;*/
            /*}*/

            /*@media screen and (min-width: 320px) and (max-width: 767px) {*/
            /*    .vi_do {*/
            /*        padding: 0px;*/
            /*    }*/
            /*}*/

        </style>

        <div class="row">
            <div class="col-md-12">
                <h2 class="">
                    {{ $videoinfo->video_name }}
                </h2>
            </div>
        </div>
        <div class="row">

            <?php
            //            dump($userid);
            ?>

            <div class="col-md-6 ">

                <div class="col-md-12 " id="video">
                    <?php
//                    dump($videoinfo)
                    ?>

                    @if($videoinfo->video_file_url != '')



                            <video
                                id="my-video"
                                class="video-js vjs-theme-sea m-3"
                                controls
                                width="450"
                                height="264"
                                preload="none"
                                poster="https://media.swncdn.com/via/5793-istockgetty-images-pluspattadis-walarput.jpg"

                                {{--                                            data-setup="{}"--}}
                            >

                                <source src="{{ $videoinfo->video_file_url }}" type="video/mp4" />
                                <p class="vjs-no-js">
                                    To view this video please enable JavaScript, and consider upgrading to a
                                    web browser that
                                    <a href="https://videojs.com/html5-video-support/" target="_blank"
                                    >supports HTML5 video</a
                                    >
                                </p>
                            </video>



                    @else

                        <h6 style="min-width: 200px; margin-top: 100px" class="text-center ">
                            Vidoe Not Abalable Please Record Now
                        </h6>

                    @endif

                </div>


            </div>
            <div class="col-md-6 ">

                <div id="header">

                </div>


                <div class="p-2">
                    <video id="record_user" class="record embed-responsive-item" autoplay playsinline
                           width="450"
                           height="264"
                    >

                    </video>
                </div>


                <!-- Modal -->
                <div class="modal fade" id="recardPlay" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">

                    <div class="modal-dialog modal-md" role="document">
                        <div class="modal-content ">
                            <div class="modal-header">
                                <h5 class="modal-title" id="exampleModalLabel">Video Preview</h5>
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                    <span aria-hidden="true">&times;</span>
                                </button>
                            </div>
                            <div class="modal-body">
                                <video id="record_video" class="embed-responsive-item vi_pq record_video" controls autoplay playsinline
                                       width="100%"
                                       height="264"
                                ></video>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-dismiss="modal">Re-record</button>
                                <button type="button" class="btn btn-primary saveRecord">Save Video</button>
                            </div>
                        </div>
                    </div>
                </div>


            </div>
        </div>

        <div class="row">
            <div class="col-md-6"></div>
            <div class="col-md-6 text-center">
                <button id="btn-start-recording" class=" btn btn-primary">Start Recording</button>
                <button id="btn-stop-recording" class=" btn btn-primary" disabled>Stop Recording</button>
            </div>
        </div>

        <div class="bt_nw">


            @if(!empty($nextid))

                <?php

//                dd(['email'=>$email,'userid'=>base64_encode($userid),'categoryid'=>$nextid]);

            ?>

{{--                    {{ route('videoInterviewCategories', ['email'=>$email,'userid'=>base64_encode($userid),'categoryid'=>$nextid]) }}--}}




                <input type="hidden" class="nextlink"
                       value="{{ route('videoInterviewCategories', ['email'=>$email,'userid'=>base64_encode($userid),'categoryid'=>$nextid]) }}">

            @else
                <input type="hidden" class="nextlink"
                       value="{{ route('thankyou',['email'=>$email,'userid'=>base64_encode($userid)]) }}">
            @endif
        </div>


    @else
        Content coming soon
    @endif

@endsection


@section('scripts')
    <script src="https://cdnjs.cloudflare.com/ajax/libs/video.js/7.10.2/video.min.js"></script>
    <script src="/js/vidoejs.logo.js"></script>

    <?php
    $get_settings = get_settings();

    $vidoeLogoUrl = '/Hirextra_logo.png';

    if (!empty($get_settings)){
        $vidoeLogoUrl =  $get_settings->video_logo_url;
    }

    //dump($get_settings);
    ?>

    @if(!empty($videoinfo))

        <script src="/js/RecordRTC.js"></script>

        <script>
            var playerCat = videojs('my-video');
            playerCat.logo({
                image: '{{ $vidoeLogoUrl }}',
                position: 'top-right',
                fadeDelay : '99999999999',
                width : '50',
            });




            $(function (){
                $('#btn-start-recording').click(function() {
                    $("#video iframe.i_fram").attr('src',  $("#video iframe.i_fram").attr('src') + '?autoplay=1');
                });
            })

            var video = document.querySelector('video.record');

            function captureCamera(callback) {
                navigator.mediaDevices.getUserMedia({audio: true, video: true}).then(function (camera) {
                    callback(camera);
                }).catch(function (error) {
                    alert('Unable to capture your camera and mic. Please check console logs.');
                    console.error(error);
                });
            }

            var RecardVideoFrame = document.querySelector('video.record_video');

            function stopRecordingCallback() {





                $('#recardPlay').modal();

                RecardVideoFrame.src = video.srcObject = null;
                RecardVideoFrame.muted = false;
                RecardVideoFrame.volume = 1;
                RecardVideoFrame.src = URL.createObjectURL(recorder.getBlob());

                $(".saveRecord").on("click", function () {
                    RecardVideoFrame.pause();
                    // get recorded blob
                    var blob = recorder.getBlob();
                    // generating a random file name
                    var fileName = getFileName('mp4');
                    // we need to upload "File" --- not "Blob"
                    var fileObject = new File([blob], fileName, {
                        type: 'video/mp4; codecs=mpeg4'
                    });
                    var formData = new FormData();
                    // recorded data
                    formData.append('video-blob', fileObject);
                    // file name
                    formData.append('video-filename', fileObject.name);
                    formData.append('video_category_id', '{{ $videoinfo->category_id }}');
                    formData.append('candidate_id', '{{ $userid }}');
                    formData.append('job_id', 'null');
                    formData.append('record_vidoe_id', '{{ $videoinfo->id }}');
                    $('#header').html('Uploading to PHP using jQuery.... file size: (' + bytesToSize(fileObject.size) + ')');

                    // var upload_url = 'https://webrtcweb.com/f/';
                    var upload_url = '{{ route('saveVideo') }}';

                    var upload_directory = upload_url;
                    var upload_directory = './uploads/';

                    // upload using jQuery
                    $.ajax({
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        url: '{{ route('saveVideo') }}', // replace with your own server URL
                        data: formData,
                        cache: false,
                        contentType: false,
                        processData: false,
                        type: 'POST',
                        success: function (response) {

                            console.log(response)

                            if (response.error == '200') {

                                var nextlink = $('.nextlink').val();

                                window.location = nextlink;

                                // console.log(nextlink)
                                // console.log('successfully uploaded recorded blob');
                                //
                                // // file path on server
                                // var fileDownloadURL = upload_directory + fileObject.name;
                                //
                                // // preview the uploaded file URL
                                // document.getElementById('header').innerHTML = '<a href="' + fileDownloadURL + '" target="_blank">' + fileDownloadURL + '</a>';
                                //
                                // // preview uploaded file in a VIDEO element
                                // document.getElementById('your-video-id').srcObject = null;
                                // document.getElementById('your-video-id').src = fileDownloadURL;
                                //
                                // // open uploaded file in a new tab
                                // window.open(fileDownloadURL);
                            } else {
                                alert(response.msg+' custom error'); // error/failure
                                location.reload();
                            }
                        }
                    });


                    recorder.camera.stop();
                    recorder.destroy();
                    recorder = null;


                });

                $("#recardPlay").on("hidden.bs.modal", function () {
                    console.log('on close')


                    $("#btn-start-recording").prop("disabled", false);
                    RecardVideoFrame.pause();
                    location.reload();
                });


                return true;


                // video.src = video.srcObject = null;
                // video.muted = false;
                // video.volume = 1;
                // video.src = URL.createObjectURL(recorder.getBlob());



                // $( "#btn-start-recording" ).prop( "disabled", false );


            }

            var recorder; // globally accessible

            document.getElementById('btn-start-recording').onclick = function () {
                this.disabled = true;

                captureCamera(function (camera) {
                    video.muted = true;
                    video.volume = 0;
                    video.srcObject = camera;

                    recorder = RecordRTC(camera, {
                        type: 'video'
                    });

                    recorder.startRecording();

                    // release camera on stopRecording
                    recorder.camera = camera;

                    // $("#video iframe.i_fram").attr('src', $("#video iframe.i_fram").attr('src') + '?autoplay=1');


                    document.getElementById('btn-stop-recording').disabled = false;
                });
            };

            document.getElementById('btn-stop-recording').onclick = function () {
                this.disabled = true;
                recorder.stopRecording(stopRecordingCallback);
            };


            // this function is used to generate random file name
            function getFileName(fileExtension) {
                var d = new Date();
                var year = d.getUTCFullYear();
                var month = d.getUTCMonth();
                var date = d.getUTCDate();
                return 'RecordRTC-' + year + month + date + '-' + getRandomString() + '.' + fileExtension;
            }

            function getRandomString() {
                if (window.crypto && window.crypto.getRandomValues && navigator.userAgent.indexOf('Safari') === -1) {
                    var a = window.crypto.getRandomValues(new Uint32Array(3)),
                        token = '';
                    for (var i = 0, l = a.length; i < l; i++) {
                        token += a[i].toString(36);
                    }
                    return token;
                } else {
                    return (Math.random() * new Date().getTime()).toString(36).replace(/\./g, '');
                }
            }
        </script>

        <script src="https://www.webrtc-experiment.com/common.js"></script>


    @endif


@endsection
