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

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;
        }
    }
    if((device.platform||'').toLowerCase() == 'android'){
        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);
            }
        );
    }else{
        cordova.InAppBrowser.open(`tel:${phoneNumber}`, "_system");
    }
    return;
}

const callthrough = (id, phoneNumber,type) =>{
    console.log('callthrough',"phoneNumber:"+phoneNumber);
    let toNumber = getTelephoneNumber(phoneNumber);
    let fromNumber = getUserNumber();
    if(nullcheck(fromNumber)){
        return;
    }

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

    if(window.localStorage.getItem("prefixEx") == ""){
        return popAlert("설정에서 내선지역번호를 저장 후 다시 시도해주세요")
    }

    let params ={
        url : `https://${serverData.cust_con_pbx_ip}:${serverData.cust_con_port}/ipxapi/v1/users/${userData.id}/callthrough?from=${settingData.callThruPrefix}${settingData.mobileNumber}&to=${toNumber}`
        ,token : window.localStorage.getArray('userData').token
    };

    requestToCm(params , (response) => {
        console.log('callthrough', 'params', JSON.stringify(params), 'response',  JSON.stringify(response));
        if(response.data.error.message == 'OK'){
            addCallHistory(id, phoneNumber,type);
            if((device.platform||'').toLowerCase() == 'android'){
                window.plugins.gntel.setCallToNumber(phoneNumber);
                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{
                cordova.InAppBrowser.open(`tel:${window.localStorage.getItem("prefixEx")}`, "_system");
            }
        }else{
            popAlert(response.data.error.message);
        }
    });
}

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

    let params = {
        url : `https://${serverData.cust_con_pbx_ip}:${serverData.cust_con_port}/ipxapi/v1/users/${userData.id}/callback?from=${fromNumber}&to=${toNumber}`
        , token : window.localStorage.getArray('userData').token
    };

    requestToCm(params , (response) => {
        console.log('callback', 'params', JSON.stringify(params), 'response',  JSON.stringify(response));
        if(response.data.error.message == 'OK'){
            popCallAction("내 휴대폰으로 발신 요청 중입니다.<br>잠시만 기다려주세요", function() {
                callDisconnect(fromNumber,toNumber, function(){
                    popAlert("취소되었습니다.");
                });
            });
            setTimeout(() => {
                closePopAlert();
            }, 5000);
            addCallHistory(id, phoneNumber,type);
        }else{
            popAlert(response.data.error.message);
        }
    });
}

const callDisconnect = (fromNumber,toNumber, cancelCallback) =>{

    let params = {
        url : `https://${serverData.cust_con_pbx_ip}:${serverData.cust_con_port}/ipxapi/v1/users/${userData.id}/disconnect?from=${fromNumber}&to=${toNumber}`
        , token : window.localStorage.getArray('userData').token
    };

    requestToCm(params , (response) => {
        console.log('callDisconnect', 'params', JSON.stringify(params), "response", JSON.stringify(response));

        if(response.data.error.message == 'OK'){
            //popAlert("취소되었습니다.");
            if(cancelCallback){
                cancelCallback();
            }
        }else{
            popAlert(response.data.error.message);
        }
    });
}

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