
let messageDuration = 2000;

function getProvinces(targetSelectorId, selected_province_id = 0) {
    fetchRefsData(get_refs_base_url + '/provinces/json', targetSelectorId, selected_province_id);
}

function getDistrictsByProvinceId(targetSelectorId, province_id, selected_district_id = 0) {
    fetchRefsData(get_refs_base_url + '/districts/json/'+province_id, targetSelectorId, selected_district_id);
}

function getCommunesByDistrictId(targetSelectorId, district_id, selected_commune_id = 0){
    fetchRefsData(get_refs_base_url + '/communes/json/'+district_id, targetSelectorId, selected_commune_id);
}

function getVillagesByCommuneId(targetSelectorId, commune_id, selected_village_id = 0) {
    fetchRefsData(get_refs_base_url + '/villages/json/'+commune_id, targetSelectorId, selected_village_id);
}

function fetchRefsData(url, targetSelectorId, selectedId ) {
    $.ajax({
        url: url,
        type:"GET",
        dataType:"json",
        success:function(response){
            $('#'+targetSelectorId).html('');
            $('#'+targetSelectorId).append('<option selected></option>');
            response.map(item =>{
                var patientOption = document.createElement('OPTION');
                patientOption.setAttribute('value',item.id);
                if(selectedId == item.id){
                    patientOption.setAttribute('selected','selected');
                }
                patientOption.text = item.name_en;
                $('#'+targetSelectorId).append(patientOption);
            })
        }
    });
}

function generate_uuid (classPrefix, targetDisplayElementId) {
    $.ajax({
        url: get_refs_base_url+"/uuid.generate/json",
        type:"GET",
        dataType:"json",
        success:function(response){
            if(response.success) $(''+targetDisplayElementId).val(classPrefix+'-'+response.data.uuid);
            else alertify.error("Can't generate uuid.")
        }
    });
}

function deleteEntityRecord(uid, url){
    var success = false
    Swal.fire({
        text: confirm_delete_record,
        icon: 'question',
        showCancelButton: true,
        cancelButtonClass:'danger',
        confirmButtonText: confirm_ok_delete,
        cancelButtonText: confirm_cancel
    }).then((result) => {
        if (result.value) {
            $.ajax({
                url: url,
                method:'POST',
                dataType:"JSON",
                data:{
                    "_token": csrf_token,
                    uid : uid,
                },
                success:function(response){
                    handleMessage(response.success, response.message)
                    setTimeout(function () {location.reload()}, messageDuration)
                    success = true
                }
            })

        }
    });
    return success
}

function restoreEntityRecord(uid, url){
    Swal.fire({
        text: confirm_restore_record,
        icon: 'question',
        showCancelButton: true,
        cancelButtonClass:'danger',
        confirmButtonText: confirm_ok_restore,
        cancelButtonText: confirm_cancel_restore,
    }).then((result) => {
        if (result.value) {
            $.ajax({
                url: url,
                method:'POST',
                dataType:"JSON",
                data:{
                    "_token": csrf_token,
                    uid : uid,
                },
                success:function(response){
                    handleMessage(response.success, response.message)
                    setTimeout(function () {location.reload()}, messageDuration)
                }
            })

        }
    });
}

function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;

    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
}

function addRejectComment(targetSelectorId){
    Swal.fire({
        html:"<p style='float: left;'>Reject Comment</p>",
        input: "text",
        showCancelButton: !0,
        position: "center-right",
        confirmButtonText: "<i class='fa fa-save mr-2'></i>Save",
        cancelButtonText: "Cancel",
        showLoaderOnConfirm: !1,
        confirmButtonColor: "#4fb51a",
        preConfirm: function (n) {
            return new Promise(function (t) {
                $.ajax({
                    url: get_refs_base_url + '/reject-comment/save',
                    method:'post',
                    dataType:'json',
                    data:{
                        "_token": csrf_token,
                        name_en: n
                    },
                    success:function(r)
                    {
                        if(!r.success){
                            Swal.showValidationMessage('Failed while saving reject comment. ' + r.errors)
                            Swal.enableButtons()
                        }
                        else {
                            t(r.data)
                        }
                    }
                })
            })
        },
        allowOutsideClick:!1,
    }).then(function (t) {
        if(!t.dismiss){
            t.value.map(item =>{
                var patientOption = document.createElement('OPTION');
                patientOption.setAttribute('value',item.id);
                patientOption.setAttribute('selected','selected');
                patientOption.text = item.reject_comment;
                $('#'+targetSelectorId).append(patientOption);
                alertify.success("Reject comment successfully added.")
            })
        }
    })
}

function customErrorAlert(error) {
    $('.custom-error-alert').remove()
    var alertComponent = document.createElement('DIV')
    alertComponent.classList.add('alert', 'alert-danger', 'custom-error-alert','col-sm-12','col-lg-6')
    alertComponent.innerHTML= _getResponseErrorMessage(error)
    document.body.append(alertComponent)
    setTimeout(function () {
        $('.custom-error-alert').remove()
    }, 10000)
}


function _getResponseErrorMessage (error) {
    if (error.message) return error.message
    if (error.errors) return 'Internal server error. please contact system administrator.'
    if (error.responseJSON) return _getCustomResponseErrorMessage(error.statusText, error.responseJSON.errors)
    return error.message === 'Network Error' ? 'Oops! Network Error. Try again later' : error.message
}

function _getCustomResponseErrorMessage (message, errObject) {
    arr = []
    var errors = [];
    for(var i in errObject) {
        errors.push(errObject[i]);
    }
    errors.forEach(item=> {
        if(Array.isArray(item)){
            item.forEach(v=> {
                arr.concat(v)
            })
        }
        else{
            arr.concat(item)
        }
        return arr
    })
    return errors.join('<br/>')
}


function list_to_tree(list) {
    var map = {}, node, roots = [], i;

    for (i = 0; i < list.length; i += 1) {
        map[list[i].id] = i; // initialize the map
        list[i].children = []; // initialize the children
    }
    for (i = 0; i < list.length; i += 1) {
        node = list[i];
        if (node.closed_parent_id !== "0") {
            // if you have dangling branches check that map[node.parentId] exists
            //console.log('node ', list[map[node.closed_parent_id]])
            if(typeof map[node.closed_parent_id] !== 'undefined') {
                list[map[node.closed_parent_id]].children.push(node);
            }
        } else {
            roots.push(node);
        }
    }
    return roots;
}

function list_to_tree_v2(flatArray, parent = null) {
    const tree = [];
    for (const item of obj.values(flatArray)) {
        if (item.closed_parent_id === parent) {
            const children = arrayToTree(flatArray, item.id);
            if (children.length) {
                item.children = children;
            }
            tree.push(item);
        }
    }
    return tree;
}

function getSampleTypeByDepartmentId(departmentId, sampleTypeControlId, selected_sample_type_id = 0) {
    $.ajax({
        url: get_refs_base_url+'/sample-type/department/'+(departmentId>0 ? departmentId : 'null'),
        type:"GET",
        dataType:"JSON",
        success:function(response){
            $('#'+sampleTypeControlId).html('');
            $('#'+sampleTypeControlId).append('<option></option>');
            response.data.map(item =>{
                var patientOption = document.createElement('OPTION');
                patientOption.setAttribute('value',item.id);
                if(selected_sample_type_id == item.id){
                    patientOption.setAttribute('selected','selected');
                }
                patientOption.text = item.name_en;
                $('#'+sampleTypeControlId).append(patientOption);
            })
        },
        error: function(response) {
        },
    });
}

function removeUserSignature() {
    $.ajax({
        url: get_refs_base_url + '/reject-comment/save',
        method:'post',
        dataType:'json',
        data:{
            "_token": csrf_token
        },
        success:function(r)
        {
            if(!r.success){
                Swal.showValidationMessage('Failed while saving reject comment. ' + r.errors)
                Swal.enableButtons()
            }
            else {
                t(r.data)
            }
        }
    })
}

function toFixedNumber(num, fixed) {
    fixed = fixed || 0;
    fixed = Math.pow(10, fixed);
    return Math.floor(num * fixed) / fixed;
}

function handleMessage(actionStatus = true, message) {
    if(actionStatus) alertify.success(message)
    else alertify.error(message)
}

function getDate(date) {
    if(date) {
        var d = new Date(date),
            month = '' + (d.getMonth() + 1),
            day = '' + d.getDate(),
            year = d.getFullYear();
        if (month.length < 2)
            month = '0' + month;
        if (day.length < 2)
            day = '0' + day;
        return [year, month, day].join('-');
    } else return '';
}
