const keysearch = document.querySelector("#noic");
let roles = document.getElementById("roles_avatar").value;

$('#customerIDType').on('change', function() {
    switch(this.value){
        case 'nokp':
            disableTypeahead();
            resetInput();
            keysearch.setAttribute("placeholder", "No Kad Pengenalan Pelanggan");
            break;
        case 'passport':
            disableTypeahead();
            resetInput();
            keysearch.setAttribute("placeholder", "No Passport Pelanggan");
            break;
        case 'name':
            enableTypeahead();
            resetName();
            keysearch.setAttribute("placeholder", "Nama Pelanggan");
            break;
    }
});
    
var bloodhound = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.whitespace,
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
        url: api_url + '/admin/searchByName?nama=%QUERY',
        wildcard:'%QUERY',
        transform: function(response) {
            return response.map(function(item) {
                return { name: item.nama,noic:item.kpbaru ? item.kpbaru : item.kplama  };
            });
        }
    },
});

function disableTypeahead() {
    if (typeof typeahead !== 'undefined') {
        typeahead.typeahead('destroy');
    }
}

function enableTypeahead() {
    // Re-initialize Typeahead with the same configuration
    typeahead = $('.typeahead').typeahead({
        hint: false,
        highlight: true,
        minLength: 3
    },
    {
        name: 'suggestions',
        source: bloodhound,
        display: 'name',
        templates: {
            empty: function(data) {
                return `<div class="empty-message">Carian <b>${data.query}</b> tidak jumpa dalam pangkalan data</div>`;
            },
            suggestion: function(data) {
                return `<div style="cursor:pointer;" onclick="redirectName('${data.noic}')">` + data.name + '<br> ' + data.noic + '</div>';
            }
        }
    });
}

function triggerEnter(){
    console.log('test');
}


function redirectName(nokp){
    Swal.fire({
        title: 'Memuatkan...',
        allowEscapeKey : false,
        allowOutsideClick: false,
        didOpen: function () {
            Swal.showLoading()
        }
    });

    if(roles == 'teller'){
        window.location.replace(`/customer/search?noic=${nokp}&&customerIDType='name'`);        
    }else{
        window.location.replace(`/khazanah/searchpelanggan?noic=${nokp}&&customerIDType='name'`);        
    }
}

function resetInput() {
    $("#button-addon2").prop("disabled",false);
    $('#noic').val('');
}

function resetName(){
    $("#button-addon2").prop("disabled",true);
    $('#noic').val('');
}