let montList  = null;
let montBtn   = null;
let montData  = [];
let partData  = [];
let nameList  = [];
const _videoMap = new Map();
let commonUri = "/api/resp-cctv/monitoring/camera"
let lange     = 0;
let _listData  = [];

$(()=>{
    montList = $(".mont-list").dxSelectBox({
        width       : 300,
        dataSource  : null,
        height      : 27,
        valueExpr   : 'monitoring_nm',
        displayExpr : 'monitoring_nm',
        stylingMode : 'outlined',
        onItemClick(e){
            partData = [];
            getDataAsync(commonUri + "/" + e.itemData.monitoring_nm, montSection);
        }
    }).dxSelectBox('instance');

    montBtn = $(".mont-btn").dxButton({
        width       : 110,
        height      : 27,
        text        : '화면 관리',
        icon        : 'preferences',
        stylingMode : 'outlined',
        onClick(){
            window.open('./monitoring-popup-manager.html','모니터링 화면 관리','width = 1200, height = 650, top = 150, left = 300, resizable=yes, scrollbars=no')
        }
    });

    fetchBaseData();
})
function fetchBaseData() {
    getDataAsync(commonUri + '/list', recvListData);
}
function recvListData(jsonData){
    _listData = jsonData;
    montList.option('dataSource', _listData);
    if (_listData.length > 0) {
        setValue(montList, _listData[0].monitoring_nm);
        getDataAsync(commonUri + "/" + _listData[0].monitoring_nm, montSection);
    }
}
function montSection(data){
    console.log(data);
    const montBox = $(".mont-box");
    montBox.empty();
    if (!data || data.length === 0) {
        let div = $("<div class='section b2 b4 dx-theme-border-color'>")
        div.html(`<div class="mont-title serve-title b2 dx-theme-border-color dx-nav-item">
            --Empty--</div>
            <div class="mont-body"><img src="/images/op/logo/logo.png"></div>`);
        return montBox.append(div);
    }
    if (!_videoMap.get('video')){
        _videoMap.set('video', new Map());
        _videoMap.set('info', new Map());
        _videoMap.set('src', new Array());
    }
    else {
        _videoMap.get('video').forEach( (obj, key)=> {
            obj.pause();
            obj.dispose();
        });
        _videoMap.clear();
        _videoMap.set('video', new Map());
        _videoMap.set('info', new Map());
        _videoMap.set('src', new Array());
    }
    data.sort(function(a,b){
        return a['monitoring_seq'] < b['monitoring_seq']? -1: a['monitoring_seq'] > b['monitoring_seq']? 1:0;
    })
    let width  = 0;
    let height = 0;
    const length = data.length;
    switch (true) {
        case length >= 0 && length <= 1:
            width  = 1;
            height = 1;
            break;
        case length >= 2 && length <= 4:
            width  = 2;
            height = 2;
            break;
        case length >= 5 && length <= 6:
            width  = 3;
            height = 2;
            break;
        case length >= 7 && length <= 9:
            width  = 3;
            height = 3;
            break;
        case length >= 10 && length <= 12:
            width  = 4;
            height = 3;
            break;
        case length >= 13 && length <= 16:
            width  = 4;
            height = 4;
            break;
        case length >= 17 && length <= 20:
            width  = 5;
            height = 4;
            break;
        case length >= 21 && length <= 24:
            width  = 6;
            height = 4;
            break;
        case length >= 25 && length <= 30:
            width  = 6;
            height = 5;
            break;
        default:
            if ( length <= 42 ){
                width  = 7;
                height = 6;
            }
            else if( length <= 56){
                width  = 8;
                height = 7;
            }
            else {
                width  = 8;
                height = 8;
            }
            break;
    }

    let divLineArr  = [];
    let divArr      = [];
    let montWidth   = 0;
    let cnt         = 0;
    montWidth = 100/width;
    montHeight = 100/height;

    for(let ii = 0 ; ii < width * height; ii++){
        let div = $("<div class='section b2 b4 dx-theme-border-color'>")

        div.css('width',"calc(" + montWidth + "%)");
        if ( data[ii] ){
            div.html(`<div class="mont-title serve-title b2 dx-theme-border-color dx-nav-item">
            ${data[ii].monitoring_seq} : ${data[ii].istllctnnm}</div>
            <video id="video${data[ii].monitoring_seq}" class="mont-body video-js" style="object-fit:fill; width=100%; height=calc(100% - 20px);"></video>`);
            _videoMap.get('info').set(data[ii].monitoring_seq, data[ii]);
            _videoMap.get('src').push(data[ii].strm_http_addr);
        }
        else {
            div.html(`<div class="mont-title serve-title b2 dx-theme-border-color dx-nav-item">
            --Empty--</div>
            <div class="mont-body"><img src="/images/op/logo/logo.png"></div>`);
        }
        divArr.push(div)
    }

    for( let ii = 0; ii < height; ii++ ){
        let div = $("<div>");
        div.css('width', "100%");
        div.css('height', "calc("+montHeight+"%)");
        div.css('display','flex');
        for(let jj  = 0; jj < width; jj++){
            div.append(divArr[cnt]);
            cnt++
        }
        divLineArr.push(div)
    }

    montBox.append(divLineArr);
    const srcArr  = Array.from(new Set(_videoMap.get('src')));
    _videoMap.get('info').forEach( (obj)=> {
        let player = videojs('video' + obj.monitoring_seq, {
                sources : [
                    { src : obj.strmhttpaddr, type : "application/x-mpegURL"}
                ],
                controls : true,
                playsinline : true,
                muted : true,
                autoplay: true,
                preload : "none",
                controlBar: {
                    'liveDisplay': false,
                    'pictureInPictureToggle': false
                }
            }
        );
        _videoMap.get('video').set(obj.monitoring_seq, player);
        player.pause();
        player.play();
    });
}
