@extends('layouts.template')
@section('header')
    <link href="https://cdnjs.cloudflare.com/ajax/libs/video.js/6.6.2/video-js.min.css" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/video.js/6.6.2/video.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/video.js/6.6.2/ie8/videojs-ie8.min.js"></script>
    <!-- videojs-flash -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/videojs-flash/2.1.0/videojs-flash.min.js"></script>
    <script src="https://cdn.sc.gl/videojs-hotkeys/0.2/videojs.hotkeys.min.js"></script>
    <link rel="stylesheet" href="{{asset('css/video_replay.css')}}">

@stop
@section('content')
@include('video_replay.layout.menubtn')
    <div class="collapse" id="collapseExample" style="margin: 5%">
        <div class="card card-body border border-white"style="background-color:steelblue;">
            <div class="icon" style="position: absolute;right:5%;top:0"><img style="transform:scaleY(-1);transform:scaleX(-1);" width=400px height=400px src="https://www.flaticon.com/premium-icon/icons/svg/1982/1982068.svg" alt="無法顯示圖片"></div>
            <div class="row " style="margin-bottom: 2%;margin-top: 2%;">
                <div class="dropdown col-xs-6 col-md-3"style='margin:1%;display:inline;'>
                    <button  class="btn-lg btn btn-outline-warning dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
                        <span style="color:navajowhite" id="seleted_goup">選擇攝影機群組</span>
                        <span class="caret"></span>
                    </button>
                    <ul id="goup_ids" class="dropdown-menu" aria-labelledby="dropdownMenu1">
                        @foreach($Goups as $goup)
                            <li id="l"style="margin-left: 5%" onclick="goup_name.value='{{$goup->goup_name}}',select_goup('{{$goup->goup_id}}'),seleted_goup.innerHTML='{{$goup->goup_name}}'">{{$goup->goup_name}}</li>
                        @endforeach
                    </ul>
                </div>
            </div>

            <form id="send" action="http://60.249.6.104:10300/realtime/play" method="POST"  onsubmit="return false">
                {{ csrf_field() }}
                <div style="color:#000" class="row">
                    <div class="col-md-6">
                            <div class="bg-light border border-primary">
                                <div  style="text-align: center" class="bg-primary"><h3>選擇多台攝影機</h3></div>
                                <div style="margin-left: 15%" id="div_cams">請先選擇攝影機群組...</div>
                                    <input type="text" id="cam_ids" name="cam_ids" hidden/>
                                    <input type="text" id="goup_name" name="goup_name" hidden/>
                            </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6">
                    <input id='sub_btn' style="width: 100%" class="btn-lg btn-success btn" type="submit" value="送出"/>
                    </div>
                </div>
            </form>
            <div style="margin-top: 5%">
            @include('video_replay.layout.progressbar')
            </div>
        </div>
    </div>

    <div id="Screens"></div>

    <!-- {{--呼叫api 取得回傳--}} -->
    <script>
        $("#send").submit(function(e) {
            btn=document.getElementById('sub_btn');
            prg_div=document.getElementById('prg_div');
            btn.disabled=true;
            prg_div.style.visibility='';
            var form = $(this);
            var url = form.attr('action');
            var txt = "";
            var channels=document.forms['send'];
            var nums=0;
            for (i = 0; i < channels.length; i++) {
                if (channels[i].checked) {
                    txt = txt + channels[i].value +',';
                    nums++;
                }
            }
            proset(nums);
            document.getElementById('cam_ids').value=txt;
            console.log(document.getElementById('cam_ids').value);
            disposeScreens();
            $.ajax({
                type: "POST",
                url: url,
                data:form.serialize(),
                dataType: 'json',
                success: function(data)
                {
                    console.log(JSON.stringify(data));
                    newScreens(data);
                    completed();
                    setTimeout(function(){
                        $('#menu').click();
                    },1000)
                    btn.removeAttribute('disabled');
                    prg_div.style.visibility=true;
                },
                error:function(data){
                    failure();
                    alert(JSON.stringify(data)+'\n'+'發生錯誤')
                    btn.removeAttribute('disabled');
                    prg_div.style.visibility=true;
                }
            });
            e.preventDefault(); // avoid to execute the actual submit of the form.
        });
    </script>

    <!-- select the cam_group -->
    <script>
        function select_goup(goup_id)
        {
            $.ajax({
                type: "GET",
                url: '{{url('playrealtime/select_goup/')}}/'+goup_id,
                dataType: 'json',
                success: function (data) {
                    str = '';
                    var i=0;
                    for (var k in data){
                        if (i % 3 == 0){
                            str+="<div class=\"row\">";
                        }
                        str+="<div style=\"margin: 1%\" class=\"form-check form-check-inline\"><input class=\"form-check-input\" type=\"checkbox\" id=\"inlineCheckbox"+data[k]['camera_id']+"\" value=\""+data[k]['camera_id']+"\"><label class=\"form-check-label\" for=\"inlineCheckbox"+data[k]['camera_id']+"\"><span></span>"+data[k]['camera_id']+"</label></div>"
                        if (i % 3 == 2){
                            str+="</div>";
                        }
                        i++;
                    }
                    document.getElementById("div_cams").innerHTML = str;
                },
                error: function (data) {
                    alert(JSON.stringify(data) + '\n' + '發生錯誤')
                }

            });
        }
    </script>


    <!-- videojs 視窗調整事件 -->
    <script>
        function update_video_width(){
            videos.forEach(element => {
                element.width(Math.floor(document.body.clientWidth/columns_cam));
            });
        }

        window.onresize = function(){
            update_video_width()
        }
    </script>
    <!-- 準備串流後播放 -->
    <script>
        var videos = new Array();
        function readyScreens(count_cam){
            videos.length = 0;
            var videoid =document.getElementsByClassName("vjs-control-bar");
            var video_option={
                preload: 'auto',
                autoplay:true,
                fluid: false,
                muted:true,

            };
            for(i=0;i<count_cam;i++){
                videos.push(videojs('video'+i,video_option));
                videos[i].ready(function() {
                    this.hotkeys({
                        volumeStep: 0.1,
                        seekStep: 5,
                        enableVolumeScroll: false, //禁用鼠标滚轮调节问音量大小
                        enableModifiersForNumbers: false
                    });

                    this.on("error",function(e){
                        // alert(this.id()+"error");
                        var index = videos.indexOf(this);

                        videos[index].src([
                            {type: "application/x-mpegURL", src: "http://d2zihajmogu5jn.cloudfront.net/bipbop-advanced/bipbop_16x9_variant.m3u8"}
                        ]);
                        // this.dispose();
                        // var content_test=document.getElementById("vdiv"+index);
                        // content_test.innerHTML="<img id=\"video"+index+"\" class=\"img-responsive errorimg\" src=\"https://cdn2.iconfinder.com/data/icons/interactive-shadow-pack/100/_-3-512.png\">"
                        // delete videos[index];
                        // vcontent_test.style.backgroundImage = "url('https://cdn2.iconfinder.com/data/icons/interactive-shadow-pack/100/_-3-512.png')";
                    });
                });


                // videoid[i].style.setProperty("display", "none", "important");
                videos[i].play();
            }
        }
    </script>

    <!-- 刪除屏幕 -->
    <script>
        function disposeScreens(){
            videos.forEach(function(obj){
                obj.dispose();
            });
        }
    </script>

    <!-- 新增屏幕 -->
    <script>
        let count_cam=0;
        let columns_cam=0
        function newScreens(urls){
            var playlists = urls;
            count_cam=playlists.length;
            columns_cam=Math.floor(Math.sqrt(count_cam));
            if (columns_cam <=1 ){
                columns_cam=count_cam;
            }
            var rows_cam=Math.ceil(count_cam/columns_cam);
            var str='';
            str+=("<div class=\"container-fluid\">");
            for(i=0;i<rows_cam;i++){
                str+=("<div class=\"row\">");
                //基數欄位左右補齊
                if(12-(Math.floor(12/columns_cam))!= 0)
                {
                    str+=("<div class=\"col-"+(12-Math.floor(12/columns_cam)*columns_cam)/2+"\" style=\"padding-left: 0px; padding-right: 0px;\">");
                    str+=("</div>");
                }
                for(j=0;j<columns_cam && (i*columns_cam+j)!=count_cam;j++){
                    str+=("<div class=\"col-"+Math.floor(12/columns_cam)+"\" style=\"padding-left: 0px; padding-right: 0px;\">");
                    str+=("<video id=\"video"+(i*columns_cam+j)+"\""+ "width=\""+(Math.floor(document.body.clientWidth/columns_cam))+"\"  class=\"video-js vjs-default-skin\"");
                    str+=("playsinline webkit-playsinline autoplay controls preload=\"auto\"");
                    str+=("x-webkit-airplay=\"true\" x5-video-player-fullscreen=\"true\" x5-video-player-typ=\"h5\" muted=\"muted\">");
                    str+=("<source src=\""+urls[(i*columns_cam+j)]+"\"");
                    str+=("type='video/rtmp'>");
                    str+=("</video>");
                    str+=("</div>");
                    console.log(urls[(i*columns_cam+j)]);
                }
                str+=("</div>");
            }
            str+=("</div>");
            document.getElementById('Screens').innerHTML=str;
            setTimeout(readyScreens(count_cam),1000);
        }
    </script>
@endsection
