<!DOCTYPE html>
<html lang="en" xmlns:th=http://www.thymeleaf.org>
<head>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width,initial-scale=1"/>
    <meta name="theme-color" content="#000000"/>
    <meta name="description" content="포항시 교통정보센터입니다"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <title>포항시 교통정보센터</title>
    <th:block th:include="/include/head.html"></th:block>
    <link rel="stylesheet" th:href="@{/css/cctv.css}">
    <script th:src="@{/js/videojs/video-7.10.2.js}"></script>
    <link rel="stylesheet" th:href="@{/css/video-7.10.2.css}">
</head>
<body id="body">
<th:block th:include="/include/admin-header.html"></th:block>
<div class="cctvWrap">
    <div class="container">
        <h2 class="admin-header">CCTV 관리</h2>
        <div th:class="tab">
            <div class="cctv active" onclick="tabActive('smart', 'cctv')">교통 CCTV</div>
            <div class="smart" onclick="tabActive('cctv', 'smart')">스마트교차로 CCTV</div>
        </div>
        <div class="admin-content">
            <div class="left">
                <div class="title">교통 CCTV 목록</div>
                <div class="list"></div>
            </div>
            <div class="right">
                <div class="title">영상화면은 30초 동안 재생됩니다. <label class="toggle-button"><input id="switch" role="switch" type="checkbox"></label></div>
                <div class="content">
                    <video id="video" class="video-js vjs-big-play-centered vjs-control-bar" playsinline style="width: 100%; height: 100%"></video>
                </div>
            </div>
        </div>
    </div>
</div>
<th:block th:include="/include/footer.html"></th:block>
</body>
</html>

<script th:inline="javascript">
    const cctv = [[${cctv}]];
    const intersection = [[${intersection}]];
    // let cctvStr = "";
    // let intersectionStr = "";
    const strMap = new Map();
    const detailMap = new Map();
    const cctvMap = new Map();
    const ixrMap  = new Map();

    const $list  = $('.admin-content .left .list');
    const $title = $('.admin-content .left .title');
    const $switch = $('#switch');

    recvCctvData(cctv);
    recvIxrData(intersection);

    $switch.on('click', function (event) {
        event.preventDefault();
        const selectTab = $('.tab > div.active').text();
        const selectUl  = $('ul.active');
        const selectDiv = $('ul.active > div');
        const selectLi  = $('li.active');
        if (!selectUl[0]) return;

        let useYn =  $(this).is(':checked') ? 1 : 0;

        let uri = '/api/traffic/hmpg-stts-update';
        let cctvId = selectUl.attr('id');
        let ixrId = "";
        let name = selectDiv.text();
        let id = cctvId;
        let isCctv = selectTab === '교통 CCTV';
        if (!isCctv) {
            uri = '/api/itcs/hmpg-stts-update';
            cctvId = selectLi.attr('id');
            ixrId = selectUl.attr('id');
            name = name.substr(0, name.indexOf(' ('));
            id = ixrId;
            if (cctvId) {
                name = name + ' - ' +selectLi.text();
                id = ixrId + ' - ' + cctvId;
            }
        }
        // let frontStr = 'ID : ' + id + '\n' +'위치 : ' + name + '\n'
        let frontStr = 'ID : ' + id + '<br>' +'위치 : ' + name + '<br>'
        let message = "해당 목록을 홈페이지에 표출 하시겠습니까?";
        if (!$(this).is(':checked')) {
            message = "해당 목록을 홈페이지에 표출 하지 않겠습니까?";
        }
        let param = {
            useYn : useYn,
            cctvId : cctvId,
            ixrId  : ixrId,
        }
        alertMessage('blue', frontStr + message, 'CCTV 관리', null, ()=>{
            getDataAsync(uri, "POST", param, null, (jsonData)=>{
                if (jsonData) {
                    // alert(jsonData.message);
                    alertMessage('blue', jsonData.message, 'CCTV 관리', null, null);
                    if (jsonData.success === 'S') {
                        $(this).prop('checked', !$(this).is(':checked'));
                        if (isCctv) {
                            getCctvData(cctvId);
                        }
                        else {
                            getIxrData(cctvId, ixrId);
                        }
                    }
                }
            }, false);
        })
        // if (confirm(frontStr + message)) {
        //     getDataAsync(uri, "POST", param, null, (jsonData)=>{
        //         if (jsonData) {
        //             alert(jsonData.message);
        //             if (jsonData.success === 'S') {
        //                 $(this).prop('checked', !$(this).is(':checked'));
        //                 if (isCctv) {
        //                     getCctvData(cctvId);
        //                 }
        //                 else {
        //                     getIxrData(cctvId, ixrId);
        //                 }
        //             }
        //         }
        //     }, false);
        // }
    })

    let video  =  videojs("video", {
        sources: [],
        controls : true,
        responsive: false,
        autoplay: true,
        muted: true,
        preload: "metadata",
    });

    let timer = null;


    function playVideo(playUrl) {
         video = videojs("video", {
            sources: [{
                src: playUrl,
                type: "application/x-mpegURL",
                crossorigin: "anonymous",
            },],
            controls : true,
            responsive: false,
            autoplay: true,
            muted: true,
            preload: "metadata",
            controlBar : {
                pictureInPictureToggle: false,
                volumePanel: false,
            }
        })
        timer = setTimeout(()=>{
            video.pause();
        }, 30 * 1000);
    }

    function closeVideo() {
        if (video) {
            if (timer) {
                clearTimeout(timer);
                timer = null;
            }
            video.pause();
            video.dispose();
            video = null;
            $('.right .content').html('<video id="video" class="video-js vjs-big-play-centered" style="width: 100%; height: 100%;"></video>');
        }
    }

    function getCctvData(cctvId) {
        getDataAsync('/api/traffic/cctv-list-all', 'POST', null, cctvId, recvCctvData, null);
    }

    function getIxrData(cctvId, ixrId) {
        getDataAsync('/api/itcs/list-all', 'POST', null, [cctvId, ixrId], recvIxrData, null);
    }

    function recvIxrData(jsonData, args) {
        if (jsonData && jsonData.length > 0) {

            jsonData.sort(function(a, b){
                return a.ixr_nm > b.ixr_nm ? 1 : a.ixr_nm < b.ixr_nm ? -1 : 0;
            });

            let intersectionStr = "";
            jsonData.forEach((obj)=>{
                let cnt = 0;
                let detailStr = "";
                obj.detail.forEach((camera)=>{
                    detailStr += `<li id="${camera.cmra_id}" class="state-${camera.cmra_use_yn}" onclick="detailClick('${camera.cmra_id}')">${camera.drct_lctn}</li>`;
                    detailMap.set(camera.cmra_id, camera);
                    if (camera.cmra_use_yn === 1) {
                        cnt++;
                    }
                });
                ixrMap.set(obj.ixr_id, obj);
                intersectionStr += `<ul id="${obj.ixr_id}" onclick="ixrClick('${obj.ixr_id}')">
                                        <div>${obj.ixr_nm} (${cnt}/${obj.detail.length})</div>
                                        <ul class="cmra-list">`;
                intersectionStr += detailStr
                intersectionStr += `</ul></ul>`;
            });
            strMap.set('smart', intersectionStr);
        }
        if ($('.smart').hasClass('active')) {
            $list.html(strMap.get('smart'));
            if (args && args.length > 0) {
                args.forEach((obj)=>{
                    if(obj) {
                        $('#' + obj).addClass('active');
                    }
                })
            }
        }
    }


    function recvCctvData(jsonData, cctvId) {
        let cctvStr = "";
        if (jsonData && jsonData.length > 0) {
            jsonData.forEach((obj)=>{
                cctvStr +=`<ul id="${obj.cctv_mngm_nmbr}" onclick="cctvClick('${obj.cctv_mngm_nmbr}')"><div class="state-${obj.hmpg_dspl_en}">${obj.istl_lctn_nm}</div></ul>`;
                cctvMap.set(obj.cctv_mngm_nmbr, obj);
            });
        }
        strMap.set('cctv', cctvStr);

        if ($('.cctv').hasClass('active')) {
            $list.html(strMap.get('cctv'));
            if (cctvId) {
                $('#' + cctvId).addClass('active');
            }
        }

    }


    function tabActive(hide, show) {
        const $show = $('.' + show);
        $('.' + hide).removeClass('active');
        $show.addClass("active");

        $list.html(strMap.get(show));
        $title.text($show.text() + ' 목록');
    }
    function cctvClick(cctvNo) {
        const obj = cctvMap.get(Number(cctvNo));
        selectToggle(cctvNo)
        if (obj) {
            const useYn = (obj.hmpg_dspl_en === 1);
            $switch.prop("checked", useYn);
            closeVideo();
            playVideo(obj.strm_http_addr);
        }
    }

    function ixrClick(ixrNo) {
        if ($('#'+ixrNo)[0] === $('ul.active')[0]) return;

        if ($('ul.active li.active')[0]) {
            $('ul.active li.active').removeClass('active');
        }
        closeVideo();

        let ixrInfo = ixrMap.get(ixrNo);
        let cnt = 0;
        ixrInfo.detail.forEach((obj)=>{
            cnt += obj.cmra_use_yn;
        });
        $switch.prop('checked', (cnt > 0));
        selectToggle(ixrNo);
    }

    function detailClick(cmraId) {
        const obj = detailMap.get(cmraId);
        $('.cmra-list > li.active').removeClass('active');
        $('#' + cmraId).addClass('active');
        if (obj) {
            const useYn = (obj.cmra_use_yn === 1);
            $switch.prop("checked", useYn);
            closeVideo();
            playVideo(obj.hmpg_cmra_url);
            //playVideo(obj.http_cmra_url); //로컬 주소
        }
    }

    function selectToggle(id) {
        $('ul.active').removeClass("active");
        $('ul#'+id).addClass('active');
    }
</script>