//다이얼(통화관련)
let callNum = ""
    ,selection = ""
    ,range = ""
    ,callNumStart = ""
    ,callNumEnd = ""
    ,frontNum = ""
    ,backNum = ""
    ,dialCheck = false
    ;

function callBack(id, phoneNumber, type){
    
    let toNumber = getTelephoneNumber(phoneNumber);
    let fromNumber = getUserNumber();
    if(nullcheck(fromNumber)){
        return;
    }

    let tempUrl = 'https://' + serverData.cust_con_pbx_ip + ':' + serverData.cust_con_port + '/ipxapi/v1/users/' + userData.id + '/callback?from='+fromNumber+'&to='+toNumber;

    cordova.plugin.http.setServerTrustMode('nocheck', function() {
        console.log('callBack','success!');
    }, function() {
        console.log('callBack','error :(');
    });
    
    cordova.plugin.http.post(tempUrl, { }, {
        Authorization: 'Bearer '+userData.token
    }, function(response) {
        let jsonData = JSON.parse(response.data);
        console.log('callBack',"jsonData:"+JSON.stringify(jsonData));
        if(!nullcheck(jsonData.error)){
            if(jsonData.error.message == 'OK'){
                popCallAction("내 휴대폰으로 발신 요청 중입니다.<br>잠시만 기다려주세요", function() {
                    callDisconnect(fromNumber,toNumber);
                });
                setTimeout(() => {
                    closePopAlert();
                }, 5000);
                addCallHistory(id, phoneNumber,type);
            }else{
                popAlert(jsonData.error.message);
            }
        }else{
            popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
        }

    }, function(response) {
        // prints 403
        console.log('callBack',"response status:"+response.status);
        //prints Permission denied
        console.log('callBack',response.error);
        popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
    });
}

function clickToCall(id, phoneNumber,type){

    // 내신번호 이면 prefix를 붙여줌
    if ( phoneNumber.length == settingData.cidLength ) {

        let etcNo = null;

        if(settingData.pbxType == 'CM'){
            for(let key in user_map){
                let user = user_map[key];
                try {
                    if ( user.cid_no == phoneNumber ) {
                        if ( user.etc_no !== 'undefined' && user.etc_no !== null && user.etc_no !== '' ) {
                            etcNo = user.etc_no;
                        }
                        break;
                    }
                } catch (e) {}
            }
        } 

        if(etcNo == null){
            phoneNumber = settingData.svcPrefixNo + phoneNumber;
        } else {
            phoneNumber = etcNo;
        }
    }

    cordova.plugins.phonedialer.call(
        '' + phoneNumber + '',
        function (success) { 
            addCallHistory(id, phoneNumber,type);
            console.log('clickToCall','Dialing succee  ded'); },
        function (err) {
            if (err == "empty") console.log('clickToCall',"Unknown phone number");
            else alert("Dialer Error:" + err);
        }
    );
    return;
}

function callthrough(id, phoneNumber,type){
    console.log('callthrough',"phoneNumber:"+phoneNumber);
    let toNumber = getTelephoneNumber(phoneNumber);
    let fromNumber = getUserNumber();
    if(nullcheck(fromNumber)){
        return;
    }
    
    let tempUrl = 'https://' + serverData.cust_con_pbx_ip + ':' + serverData.cust_con_port + '/ipxapi/v1/users/' + userData.id + '/callthrough?from='+settingData.mobileNumber+'&to='+toNumber;
    console.log("callthrough tempUrl ::",tempUrl);

    if(window.localStorage.getItem("prefixEx") == ""){
        console.log('callthrough',"내선 값이 없음");
    }else{
        console.log('callthrough',"내선 값이 있음");
    }

    cordova.plugin.http.setServerTrustMode('nocheck', function() {
        console.log('callthrough','setServerTrustMode success!');
        //console.log("serverdata",window.localStorage.getItem("prefixEx"));
    }, function(e) {
        console.log('callthrough','setServerTrustMode error :', e);
    });
    console.log('callthrough',"실행");
    cordova.plugin.http.post(tempUrl, { }, {
        Authorization: 'Bearer '+userData.token
    }, function(response) {
        console.log('callthrough',response);
        let jsonData = JSON.parse(response.data);
        if(!nullcheck(jsonData.error)){
            console.log('callthrough',"error메시지",JSON.stringify(jsonData))
            if(jsonData.error.message == 'OK'){

                console.log('callthrough',window.localStorage.getItem("prefixEx"));
                if(window.localStorage.getItem("prefixEx") == ""){
                    alert("설정에서 내선지역번호를 저장 후 다시 시도해주세요")
                }else{

                    addCallHistory(id, phoneNumber,type);
                    cordova.plugins.phonedialer.call(
                        '' + window.localStorage.getItem("prefixEx") + '',
                        function(success) { console.log('callthrough','Dialing succee  ded'); },
                        function(err) {
                            if (err == "empty") console.log('callthrough',"Unknown phone number");
                            else alert("Dialer Error:" + err);
                        }
                    );
                }
            }else{
                popAlert(jsonData.error.message);
            }
        }else{
            popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요", response);
        }

    }, function(response) {
        popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요", response);
    });
}

// TODO: dhlee: 임의로 언스크린드 작성
function callunscreened(id, phoneNumber,type){
    
    console.log('callunscreened',"phoneNumber:"+phoneNumber);
    let toNumber = getTelephoneNumber(phoneNumber);
    let fromNumber = getUserNumber();
    if(nullcheck(fromNumber)){
        return;
    }

    let tempUrl = 'https://' + serverData.cust_con_pbx_ip + ':' + serverData.cust_con_port + '/ipxapi/v1/users/' + userData.id + '/callthrough2?from='+settingData.mobileNumber+'&to='+toNumber;
    console.log('callunscreened',"tempUrl 0 "+userData.token+":::"+tempUrl);

    if(window.localStorage.getItem("prefixEx") == ""){
        console.log('callunscreened',"내선 값이 없음");
    }else{
        console.log('callunscreened',"내선 값이 있음");
    }

    cordova.plugin.http.setServerTrustMode('nocheck', function() {
        console.log('callunscreened','success!');
        //console.log("serverdata",window.localStorage.getItem("prefixEx"));
    }, function() {
        console.log('callunscreened','error :(');
    });
    cordova.plugin.http.post(tempUrl, { }, {
        Authorization: 'Bearer '+userData.token
    }, function(response) {
        console.log('callunscreened',response)
        let jsonData = JSON.parse(response.data);
        if(!nullcheck(jsonData.error)){
            console.log('callunscreened',"error메시지",JSON.stringify(jsonData))
            if(jsonData.error.message == 'OK'){

                console.log('callunscreened',window.localStorage.getItem("prefixEx"));
                if(window.localStorage.getItem("prefixEx") == ""){
                    alert("설정에서 내선지역번호를 저장 후 다시 시도해주세요")
                }else{

                    addCallHistory(id, phoneNumber,type);
                    cordova.plugins.phonedialer.call(
                        '' + window.localStorage.getItem("prefixEx") + '',
                        function(success) { console.log('callunscreened','Dialing succee  ded'); },
                        function(err) {
                            if (err == "empty") console.log('callunscreened',"Unknown phone number");
                            else alert("Dialer Error:" + err);
                        }
                    );
                }
            }else{
                popAlert(jsonData.error.message);
            }
        }else{
            popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
        }

    }, function(response) {
        //popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
    });
}

function callDisconnect(fromNumber,toNumber){
    
    let tempUrl = 'https://' + serverData.cust_con_pbx_ip + ':' + serverData.cust_con_port + '/ipxapi/v1/users/' + userData.id + '/disconnect?from='+fromNumber+'&to='+toNumber;
    console.log('callDisconnect',"clickToCall tempUrl"+tempUrl);
    cordova.plugin.http.setServerTrustMode('nocheck', function() {
        console.log('callDisconnect','success!');
    }, function() {
        console.log('callDisconnect','error :(');
    });
    cordova.plugin.http.post(tempUrl, { }, {
        Authorization: 'Bearer '+userData.token
    }, function(response) {
        let jsonData = JSON.parse(response.data);
        console.log('callDisconnect',"jsonData:"+JSON.stringify(jsonData));

        if(!nullcheck(jsonData.error)){
            if(jsonData.error.message == 'OK'){
                popAlert("취소되었습니다.");
            }else{
                popAlert(jsonData.error.message);
            }
        }else{
            popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
        }
    }, function(response) {
        // prints 403
        console.log('callDisconnect',"response status:"+response.status);
        //prints Permission denied
        console.log('callDisconnect',response.error);
        popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
    });
}

function closeCalling(){
    $(".bg_calling").removeClass("on");
    $(".bg_calling").remove();
}

function resetCaret(){
    selection = "";
    range = "";
    callNumStart = "";
    callNumEnd = "";
    frontNum = "";
    backNum = "";
}

function setCaret(){
    selection = document.getSelection();
    range = selection.getRangeAt(0);
    callNumStart = range.startOffset;
    callNumEnd = range.endOffset;

    frontNum = callNum.substring(0, callNumStart);
    backNum = callNum.substring(callNumEnd, callNum.length);
    console.log('setCaret',"frontNum::"+frontNum+"::backNum::"+backNum);
}

function refreshButtuons() {

    let cust_func_code = settingData.cust_func_code;

    $(".call_back").hide();
    $(".call_through").hide();
    $(".click_to_call").hide();

    if (cust_func_code == "1") {
        $(".call_back_div").html("<i class='bi bi-telephone'></i>통화(C.B)");
        $(".call_back").show();
    } else if(cust_func_code == "2") {
        $(".call_through_div").html("<i class='bi bi-telephone'></i>통화(C.T)");
        $(".call_through").show();
    } else if(cust_func_code == "3") {
        $(".call_through_div").html("<i class='bi bi-telephone'></i>안심통화");
        $(".call_through").show();
    } else if(cust_func_code == "4") {
        $(".call_through_div").html("<i class='bi bi-telephone'></i>안심통화");
        $(".click_to_call_div").html("<i class='bi bi-phone'></i>휴대폰통화");
        $(".call_through").show();
        $(".click_to_call").show();
    } else if(cust_func_code == "5") {
        $(".call_through_div").html("<i class='bi bi-telephone'></i>안심통화");
        $(".click_to_call_div").html("<i class='bi bi-phone'></i>5G통화");
        $(".call_through").show();
        $(".click_to_call").show();
    } else if(cust_func_code == "6") {
        $(".call_back_div").html("<i class='bi bi-telephone'></i>통화(C.B)");
        $(".call_through_div").html("<i class='bi bi-telephone'></i>통화(C.T)");
        $(".call_back").show();
        $(".call_through").show();
    } else if(cust_func_code == "7") {
        $(".call_back_div").html("<i class='bi bi-telephone'></i>통화(C.B)");
        $(".call_through_div").html("<i class='bi bi-telephone'></i>통화(C.T)");
        $(".click_to_call_div").html("<i class='bi bi-phone'></i>휴대폰통화");
        $(".call_back").show();
        $(".call_through").show();
        $(".click_to_call").show();
    } else if(cust_func_code == "8") {
        $(".call_through_div").html("<i class='bi bi-telephone'></i>내선통화");
        $(".click_to_call_div").html("<i class='bi bi-phone'></i>휴대폰통화");
        $(".call_through").show();
        $(".click_to_call").show();
    } else if(cust_func_code == "9") {
        $(".call_back_div").html("<i class='bi bi-telephone'></i>통화(C.B)");
        $(".click_to_call_div").html("<i class='bi bi-phone'></i>휴대폰통화");
        $(".call_back").show();
        $(".click_to_call").show();
    }
}

$(()=>{
    $(".calling_num").on("click", function(event){
        event.stopPropagation();
        setCaret();
    });

    $(".dial_box button").on("touchstart", function(event){

        callNum = $(".calling_num").html();

        $(this).addClass("selected");
        if(callNum.length > 15){
            if(dialCheck){
            }else{
                dialCheck = true;
                setTimeout(() => {
                    dialCheck = false;
                }, 2000);
                toast("16자리 까지 입력 됩니다");
            }
            resetCaret();
            return;
        }

        console.log('dial_box button on click',"oscillator1.start",oscillator1);
        event.preventDefault();

        freqs = $(this).data("freq").split(",");
        dialTone(parseInt(freqs[0]), parseInt(freqs[1]));

        setTimeout(() => {
            stopOscillator();
        }, 2000);

        event.stopPropagation();
        if(frontNum.length == 0 && backNum.length == 0){
            callNum = callNum + $(this).data("val");
            callNum = callNum.substring(0,16);
            $(".calling_num").html(callNum);
        } else {
            callNum = frontNum + $(this).data("val") + backNum;
            callNum = callNum.substring(0,16);
            $(".calling_num").html(callNum);

            let newrange = new Range();
            newrange.setStart(Num.firstChild, frontNum.length+1);
            console.log('dial_box button on click',"frontNum"+frontNum.length);
            newrange.setEnd(Num.firstChild, frontNum.length+1);
            window.getSelection().removeAllRanges();
            window.getSelection().addRange(newrange);
            setCaret();
        }
    });

    $(".dial_box button").on("touchend", function(event){
        event.preventDefault();
        setTimeout(()=>{ stopOscillator(); },100); //바로 끊으면 다이얼소리가 짤리는것처럼 느껴짐
        $(this).removeClass("selected");
        searchPad();
    });

    $(".del_digit").on("click", function(e){
        e.stopPropagation();
        if(frontNum.length == 0 && backNum.length == 0){
            callNum = callNum.slice(0, -1);
            $(".calling_num").html(callNum);
            searchPad();
        } else {
            callNum = frontNum.slice(0, -1) + backNum;
            $(".calling_num").html(callNum);
            searchPad();
            let newrange = new Range();
            newrange.setStart(Num.firstChild, frontNum.length-1);
            newrange.setEnd(Num.firstChild, frontNum.length-1);
            console.log('del_digit on click',frontNum.length);
            window.getSelection().removeAllRanges();
            window.getSelection().addRange(newrange);
            setCaret();
            if(frontNum.length < 2){
                resetCaret();
            }
        }
    });

    $(".del_digit").on("taphold", function(){
        $(".calling_num").html("");
        resetCaret();
        callNum ="";
        searchPad();
    });

    $(".sel_other").on("click", function(event){
        //alert("sel_other");
        event.stopPropagation();
        selectDialNumber(searchContactByNumber,callNum);
    });

    $(".src_result_box").on("click", function(){
        console.log('src_result_box on click');
        let firstContact =  searchContactByNumber[0];

        let telephone = searchContactByNumber[0].phoneNumbers.find(item => new RegExp(callNum).test(item.normalizedNumber))
        console.log('src_result_box on click','telephone = ' + JSON.stringify(telephone));
        let telephoneNumber = telephone.normalizedNumber

        $(".calling_num").html(telephoneNumber);
        callNum = telephoneNumber;

        searchPad();
    });

    $('.ui-mobile-viewport').on("click", ".dial_pad_list", function(){

        let telephoneNumber = $(this).data("telephonenumber");

        console.log('dial_pad_list on click',telephoneNumber);
        $(".calling_num").html(telephoneNumber);
        callNum = telephoneNumber;

        searchPad();

        setTimeout(() => {
            $(".bg_calling").remove();
        }, 200);
    });

    //call_back
    $(".call_back").on("click", function(){
        console.log('call_back on click');

        let oriToNumber = $(".calling_num").html();
        $(".calling_num").html("");
        callNum = "";
        $(".src_result_box").hide();
        if(nullcheck(oriToNumber)){
            let callHistory = window.localStorage.getArray("callHistory");
            
            if( nullcheck(callHistory)){
                popAlert("전화 번호를 확인해 주세요");
                return
            }

            $(".calling_num").html(callHistory[0].num);
            callNum = callHistory[0].num;
            return;
        }

        // TODO: dhlee: 공통처리로 변경
        callBack("-1"+oriToNumber, oriToNumber, "기타");

    });

    //클릭콜 버튼
    $(".click_to_call").on("click", function(){

    // TODO: dhlee: 임의로 언스크린드로 변경

        let oriToNumber = $(".calling_num").html();
        $(".calling_num").html("");
        callNum = "";
        $(".src_result_box").hide();
        if(nullcheck(oriToNumber)){
            let callHistory = window.localStorage.getArray("callHistory");

            if( nullcheck(callHistory)){
                popAlert("전화 번호를 확인해 주세요");
                return
            }

            $(".calling_num").html(callHistory[0].num);
            callNum = callHistory[0].num;
            return;
        }

        clickToCall("-1"+oriToNumber, oriToNumber, "기타");
    });
    
    //콜스루 버튼
    $(".call_through").on("click", function(){

        let oriToNumber = $(".calling_num").html();
        $(".calling_num").html("");
        callNum = "";
        $(".src_result_box").hide();
        if(nullcheck(oriToNumber)){
            let callHistory = window.localStorage.getArray("callHistory");

            if( nullcheck(callHistory)){
                popAlert("전화 번호를 확인해 주세요");
                return
            }

            $(".calling_num").html(callHistory[0].num);
            callNum = callHistory[0].num;
            return;
        }

        viewCallInfo(oriToNumber);

        let timeout = devicePlatform == "iOS" ? 0 : 3000;

        setTimeout(() => {
            callthrough("-1"+oriToNumber, oriToNumber, "기타");
        }, timeout);
    });
    
    // 키패드 버튼 배치
    refreshButtuons();
});