@extends('backend.layout')
@section('title', $title)

@section('headerStyles')

    <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;
        }
        .margaria{
            margin-bottom: 16px;
        }
        


    </style>
@endsection

@section('content')
    {!! getBreadcrumbs(
               array(
               'dashboard'=>'Home',
               'admin.videos.videos'=>'Videos',
               ''=>'Add New'
               ),'Add New Video'
            ) !!}

    <div class="content mt-3">
        <div class="animated fadeIn">
            <div class="row">
                <div class="col-md-12">
                    <div class="card">

                        <div class="card-body card-block">
							@if (Session::has('flash_message'))
                            <br/>
                            <div class="alert alert-success alert-dismissable">
                                <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                                <strong>{{ Session::get('flash_message' ) }}</strong>
                            </div>
                        @endif
                            <form method="POST" id="videos" action="{{ route('admin.videos.addNewCategoriesVideos') }}"
                                  accept-charset="UTF-8" class="form-horizontal" enctype="multipart/form-data">
                                {{ csrf_field() }}
                                <input type="hidden" name="id" value="{{ $id }}">

                                <div class="row form-group">
                                    <div class="col col-md-3">
                                        <label for="hf-email" class=" form-control-label">Category</label>
                                    </div>
                                    <div class="col-12 col-md-9">
                                        <select name="category_id" id="category_id" class="form-control">
                                            <option value="">Select Category</option>
                                            <?php
                                            $categories = getCategories(); ?>
                                            @foreach($categories as $ks=>$s)
                                                <option
                                                    value="{{ $ks }}" {{ (!empty(old('category_id')) && old('category_id')==$ks)  ? 'selected' : ((($record) && ($record->category_id == $ks)) ? 'selected' : '') }}
                                                >
                                                    {{ $s }}
                                                </option>
                                            @endforeach
                                        </select>
                                        @if ($errors->has('category_id'))
                                            <span
                                                class="text-danger help-block">{{ $errors->first('category_id') }}</span>
                                        @endif
                                    </div>
                                </div>

                                <div class="row form-group">
                                    <div class="col col-md-3">
                                        <label for="hf-email" class=" form-control-label">Name</label>
                                    </div>
                                    <div class="col-12 col-md-9">

                                        <input class="form-control" id="video_name" type="text"
                                               placeholder="Name"
                                               name="video_name"
                                               value="{{ !empty(old('video_name')) ? old('video_name') : ((($record) && ($record->video_name)) ? $record->video_name : '') }}">
                                        @if ($errors->has('video_name'))
                                            <span
                                                class="text-danger help-block">{{ $errors->first('video_name') }}</span>
                                        @endif
                                    </div>
                                </div>
                                {{--                                <div class="row form-group">--}}
                                {{--                                    <div class="col col-md-3">--}}
                                {{--                                        <label for="hf-email" class=" form-control-label">Url</label>--}}
                                {{--                                    </div>--}}
                                {{--                                    <div class="col-12 col-md-9">--}}

                                {{--                                        <input class="form-control" id="video_url" type="text"--}}
                                {{--                                               placeholder="Url"--}}
                                {{--                                               name="video_url"--}}
                                {{--                                               value="{{ !empty(old('video_url')) ? old('video_url') : ((($record) && ($record->video_url)) ? $record->video_url : '') }}">--}}
                                {{--                                        @if ($errors->has('video_url'))--}}
                                {{--                                            <span--}}
                                {{--                                                class="text-danger help-block">{{ $errors->first('video_url') }}</span>--}}
                                {{--                                        @endif--}}
                                {{--                                    </div>--}}
                                {{--                                </div>--}}

                                <div class="row form-group">
                                    <div class="col col-md-3">
                                        <label for="hf-email" class=" form-control-label">Duration</label>
                                    </div>
                                    <div class="col-12 col-md-9">

                                        <input class="form-control" id="video_duration" type="number"
                                               placeholder="Duration" readonly
                                               name="video_duration"
                                               value="2">
                                        @if ($errors->has('video_duration'))
                                            <span
                                                class="text-danger help-block">{{ $errors->first('video_duration') }}</span>
                                        @endif
                                    </div>
                                </div>

                                <div class="row form-group">
                                    <div class="col col-md-3">
                                        <label for="hf-email" class=" form-control-label">Status</label>
                                    </div>
                                    <div class="col-12 col-md-9">
                                        <select name="status" id="status" class="form-control">
                                            <?php
                                            $status = allStatuses('general'); ?>
                                            @foreach($status as $ks=>$s)
                                                <option
                                                    value="{{ $ks }}" {{ (!empty(old('status')) && old('status')==$ks)  ? 'selected' : ((($record) && ($record->status == $ks)) ? 'selected' : '') }}
                                                >
                                                    {{ $s }}
                                                </option>
                                            @endforeach
                                        </select>
                                        @if ($errors->has('status'))
                                            <span class="text-danger help-block">{{ $errors->first('status') }}</span>
                                        @endif
                                    </div>
                                </div>

                                <div class="card-footer">
                                    <button type="submit" class="btn btn-primary btn-sm">
                                        <i class="fa fa-dot-circle-o"></i> Submit
                                    </button>
                                    <button type="reset" class="btn btn-danger btn-sm">
                                        <i class="fa fa-ban"></i> Reset
                                    </button>
                                </div>
                            </form>
                        </div>






                    @if(!empty($record))



                            <div class="row">
                                <div class="col-md-6">
                                    <h2>
                                        Old Record Video
                                    </h2>



                                    @if($record->video_url != '' )

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

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

                                            <source src="{{ $record->video_file_url }}"  type="video/mp4" />

                                        </video>


{{--                                        <video width="100%" class="newrecord" height="350" controls playsinline>--}}
{{--                                            <source src="{{ $record->video_file_url }}" type="video/webm">--}}
{{--                                            Your browser does not support the video tag.--}}
{{--                                        </video>--}}
                                    @else

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

                                    @endif


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

                                    <h2 class="margaria">
                                        New Record Section
                                    </h2>


                                    <div id="header">
                                        <span class="countdown"></span>
                                    </div>


                                    <div class="">


{{--                                        <video--}}

{{--                                            id="my-video-user"--}}
{{--                                            class="video-js vjs-theme-sea record embed-responsive-item"--}}
{{--                                            controls--}}
{{--                                            preload="auto"--}}
{{--                                            width="450"--}}
{{--                                            height="264"--}}

{{--                                        >--}}

{{--                                        </video>--}}

                                        <video class="record embed-responsive-item" autoplay playsinline
                                               width="450"
                                               height="264"
                                        >

                                        </video>
										

                                        <!-- 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="710"></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>
										
										<!-- Modal -->
                                        <div class="modal fade" id="manaually_upload" 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">Upload Video
                                                         </h5>
                                                        <button type="button" class="close" data-dismiss="modal"
                                                                aria-label="Close">
                                                            <span aria-hidden="true">&times;</span>
                                                        </button>
                                                    </div>
													<form id="maualupload" enctype= multipart/form-data method="post">
                                                    <div class="modal-body">
                                                        <input type="file" name="file_name" accept="" />
                                                    </div>
                                                    <div class="modal-footer">@csrf
                                                        
                                                        <button type="submit" class="btn btn-primary saveRecordmanually">Upload
                                                            Video
                                                        </button>
                                                    </div>
													</form>
                                                </div>
                                            </div>
                                        </div>
										
										
                                    </div>

                                    <div class="col-md-12 text-center">
										<button id="btn-manually-upload" class=" btn btn-primary">Manually Upload Video
                                        </button>
                                        <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>


                                    {{--                                    <video width="100%" height="240" controls >--}}
                                    {{--                                        <source id="your-video-id"  src="" type="video/webm">--}}
                                    {{--                                        Your browser does not support the video tag.--}}
                                    {{--                                    </video>--}}


                                </div>
                            </div>


                        @endif

                    </div>
                </div>
            </div>
        </div><!-- .animated -->
    </div><!-- .content -->

@endsection
@section('footerScripts')
{{--    <script src="https://vjs.zencdn.net/7.10.2/video.min.js"></script>--}}
<script src="https://cdnjs.cloudflare.com/ajax/libs/video.js/7.10.2/video.min.js"></script>

<?php
$get_settings = get_settings();

$vidoeLogoUrl = '/Hirextra_logo.png';

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

//dump($get_settings);
?>

    <script src="{{ asset('js/vidoejs.logo.js') }}"></script>

    @if(!empty($record))
        <script src="{{ asset('js/RecordRTC.js') }}"></script>


        <script> 
             
               
			$("#btn-manually-upload").on("click",function(){
				$('#manaually_upload').modal();
			});
            var playerCat = videojs('my-video');
            playerCat.logo({
                image: '{{ $vidoeLogoUrl }}',
                position: 'top-right',
                // fadeDelay : '99999999999',
                fadeDelay: null,
                hideOnReady : false,
                width : '50',
            });



            function CountDown(duration, display) {
                if (!isNaN(duration)) {
                    var timer = duration, minutes, seconds;

                    var interVal = setInterval(function () {
                        minutes = parseInt(timer / 60, 10);
                        seconds = parseInt(timer % 60, 10);

                        minutes = minutes < 10 ? "0" + minutes : minutes;
                        seconds = seconds < 10 ? "0" + seconds : seconds;

                        $(display).html("<b>" + minutes + "m : " + seconds + "s" + "</b>");
                        if (--timer < 0) {
                            timer = duration;
                            SubmitFunction();
                            $('#display').empty();
                            clearInterval(interVal)
                        }
                    }, 1000);
                }
            }

            let 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);
                });
            }

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

                $("span.countdown").html('00m : 00s');
                $('span.countdown').hide();
                var RecardVideoFrame = document.querySelector('video.record_video');
                var NewRecardVideoFrame = document.querySelector('video.newrecord');

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



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

                $(".saveRecord").on("click", function () {
                    console.log('on save ')


                    // 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('cate', '{{ $record->id }}');
                    $('#header').html('Uploading to PHP using jQuery.... file size: (' + bytesToSize(fileObject.size) + ')');

                    // var upload_url = 'https://webrtcweb.com/f/';
                    // var upload_url = 'save.php';
                    {{--var upload_url = '{{ route('saveCategoryVideo') }}';--}}

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

                    recorder.camera.stop();
                    // upload using jQuery
                    $.ajax({
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        url: '{{ route('saveCategoryVideo') }}', // replace with your own server URL
                        data: formData,
                        cache: false,
                        contentType: false,
                        processData: false,
                        type: 'POST',
                        success: function (response) {
                            if (response.msg === 'success') {
                                console.log('successfully uploaded recorded blob');

                                location.reload();
                            } else {
                                // alert(response); // error/failure
                                location.reload();
                            }


                        }
                    });
				});
				


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

                    $("#btn-start-recording").prop("disabled", false);
                    if (NewRecardVideoFrame) {
                        NewRecardVideoFrame.pause();

                    }
                    if (RecardVideoFrame) {
                        RecardVideoFrame.pause();
                    }

                    location.reload();

                });


                return true;


            }

            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;

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

                setTimeout(function () {
                    $('#btn-stop-recording').trigger('click')

                }, 120000);


                $('span.countdown').show();

                CountDown(120, $('span.countdown'));


            };

            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
