$(function(){
    //Initial datatable after page successfuly loaded
    var dtTable;
    makeTooltip();

    //Client Type Change
    $('#client_type').change(function(){
        let valData = $(this).val();
        changeClientType(valData);
    });

    //Form Submit
    $('#form_add_edit_auth').submit(function(){
        requestAddEditData();
    });

    $('#form_filter_data').submit(function(){
        toDataTable();
    });

    toDataTable();
});

function changeClientType(valData){
    if(valData == '0'){
        $('#v_client_id, #tooltip_client_secret').addClass('hide');
        $('#v_client_secret').removeClass('col-sm-12').addClass('col-sm-6');
    }else{
        $('#v_client_id, #tooltip_client_secret').removeClass('hide');
        $('#v_client_secret').removeClass('col-sm-6').addClass('col-sm-12');
    }
}

function toDataTable(){
    let clientTypeFilter = $('#form_filter_data #client_type_filter').val(),
        pencarian = $('#form_filter_data #pencarian').val();
    var rows = [
            { "data": "check_data" },
            { "data": "client_id" },
            { "data": "client_type_desk" },
            { "data": "client_secret" },
            { "data": "token_expired", "class": "text-center" }
          ];

    dtTable = $('#tbl_auth_store_client').on( 'error.dt', function ( e, settings, techNote, message ) {
        alertWarning('Terjadi kesalahan datatable kode : '+ techNote);
    }).DataTable({
        "processing": true,
        "serverSide": true,
        "select": false,
        "autoWidth": false,
        "buttons": [
            {
                text: '<i class="fas fa-info-circle"></i> Detail',
                className: 'btn btn-icon icon-left btn-light btn-detail-data',
                action: function(e, dt, node, config) {
                    let dataChecked = $('[name="mycheck[]"]:checked');
                    if(dataChecked.length != 1){
                        alertWarning("Mohon pilih 1 data untuk melihat detailnya");
                    }else{
                        let dataId = $(dataChecked).val();
                        detailDataAuthClient(dataId);
                    }
                }
            },
            {
                text: '<i class="fas fa-retweet"></i> Reset',
                className: 'btn btn-icon icon-left btn-light btn-reset-data',
                action: function(e, dt, node, config) {
                    let dataChecked = $('[name="mycheck[]"]:checked');
                    if(dataChecked.length != 1){
                        alertWarning("Mohon pilih 1 data untuk melihat detailnya");
                    }else{
                        let dataId = $(dataChecked).val();
                        let callBackProc = function(){
                            resetSecretKeyDataAuthClient(node, dataId);
                        }
                        confirmResetData('Secret Key', callBackProc);
                    }
                }
            },
            {
                text: '<i class="fas fa-plus"></i> Tambah',
                className: 'btn btn-icon icon-left btn-light btn-add-data',
                action: function(e, dt, node, config) {
                    openModalTambah();
                }
            },
            {
                text: '<i class="fas fa-edit"></i> Edit',
                className: 'btn btn-icon icon-left btn-light btn-edit-data hide',
                action: function(e, dt, node, config) {
                    alertWarning("Anda tidak memiliki hak akses...");
                }
            },
            {
                text: '<i class="fas fa-trash"></i> Hapus',
                className: 'btn btn-icon icon-left btn-light btn-delete-data',
                action: function(e, dt, node, config) {
                    let dataChecked = $('[name="mycheck[]"]:checked');
                    if(dataChecked.length <= 0){
                        alertWarning("Mohon pilih minimal 1 data untuk di hapus");
                    }else{
                        let callBackDelete = function(){
                            deleteDataAuth();
                        }

                        confirmDeleteData(callBackDelete);
                    }
                }
            }
        ],
        "ajax": {
            "url": baseUrl + "auth_client/getJsonDataAuthClientStore",
            "type": "POST",
            "data": function ( d ) {
                d.client_type = clientTypeFilter;
                d.pencarian = pencarian;
            },
            complete: function(resp){
                $('#tbl_auth_store_client tbody tr td:not(:first-child)').click(function(){
                    let idData = $(this).parent().attr('id');
                    manipulateCheckBox(idData);
                });
                manipulateButtonByUser(resp.responseJSON.user_type);
            }
        },
        "columns": rows
    });

    $('.mydt-button .dt-buttons').removeClass('btn-group');
}

function manipulateButtonByUser(userType){
    if(userType != '0'){
        $('.btn-reset-data, .btn-add-data, .btn-edit-data, .btn-delete-data').remove();
    }
}

function detailDataAuthClient(dataId){
    $('#modal_detail').modal({
        backdrop: "static"
    });

    let dest = baseUrl + "auth_client/getDataDetailAuthClientJson",
        data = {id: dataId};

    let loaderCall = function(){
        blockUiElement('#modal_content_detail', 'Load Detail Data...');
    }
    let loaderClose = function(){
        unblockUiElement('#modal_content_detail');
    }

    processDataJson('POST', dest, data, loaderCall, loaderClose).then(function(data){
        var rc = data.response_code,
            rmsg = data.response_message,
            rdata = data.response_data;
        if(rc == '00'){
            manipulateModalBodyDetail(rdata, rmsg, 'detail');
        }else{
            let tutupModal = function(){
                closeModal('#modal_detail');
            }
            alertWarning(rmsg, tutupModal);
        }
    });
}

function resetSecretKeyDataAuthClient(node, dataId){
    $(node).addClass('btn-progress');
    $('.btn-detail-data, .btn-add-data, .btn-edit-data, .btn-delete-data').addClass('disabled');

    let loaderCall = function(){
        blockUiElement('#tbl_auth_store_client', '');
    }
    let loaderClose = function(){
        unblockUiElement('#tbl_auth_store_client');

        $(node).removeClass('btn-progress');
        $('.btn-detail-data, .btn-add-data, .btn-edit-data, .btn-delete-data').removeClass('disabled');
    }

    let dest = baseUrl + "auth_client/resetSecretKeyDataAuthClientJson",
        data = {id: dataId};

    processDataJson('POST', dest, data, loaderCall, loaderClose).then(function(data){
        var rc = data.response_code,
            rmsg = data.response_message,
            rdata = data.response_data;
        if(rc == '00'){
            manipulateModalBodyDetail(rdata, rmsg, 'reset');
            $('#modal_detail').modal({
                backdrop: "static"
            });

            dtTable.ajax.reload( null, false );
        }else{
            alertWarning(rmsg);
        }
    });
}

function openModalTambah(){
    $('#form_add_edit_auth').attr('data-modul', 'insert');
    $('#form_add_edit_auth .modal-title').text('Tambah data auth client store');
    $("#form_add_edit_auth")[0].reset();
    $('#client_type').val('0').trigger('change');
    $('#modal_add_edit_auth').modal({
        backdrop: "static"
    });
}

function deleteDataAuth(){
    $('.btn-delete-data').addClass('btn-progress');
    $('.btn-detail-data, btn-reset-data, .btn-add-data, .btn-edit-data').addClass('disabled');

    let loaderCall = function(){
        blockUiElement('#tbl_auth_store_client', 'Proses delete data...');
    }
    let loaderClose = function(){
        unblockUiElement('#tbl_auth_store_client');

        $('.btn-delete-data').removeClass('btn-progress');
        $('.btn-detail-data, btn-reset-data, .btn-add-data, .btn-edit-data').removeClass('disabled');
    }

    let dest = baseUrl + "auth_client/deleteDataAuthClientJson",
        data = [];
    let dataChecked = $('[name="mycheck[]"]:checked');
    $.each(dataChecked, function(i, v){
        let vData = $(v).val();
        data.push(vData);
    });

    data = {id:data};
    processDataJson('POST', dest, data, loaderCall, loaderClose).then(function(data){
        var rc = data.response_code,
            rmsg = data.response_message,
            rdata = data.response_data;
        if(rc == '00'){
            let callSccss = function(){
                dtTable.ajax.reload( null, false );
            }
            alertSuccess(rmsg, callSccss);
        }else{
            alertWarning(rmsg);
        }
    });
}

function requestAddEditData(){
    let modul   = $('#form_add_edit_auth').attr('data-modul');
    let urldest = (modul == 'insert') ? baseUrl + "auth_client/addAuthClientStore" : baseUrl + "auth_client/editAuthClientStore";
    let dataSend= $('#form_add_edit_auth').serialize();
    let loaderCall = function(){
        blockUiElement('#form_add_edit_auth', 'Memproses form request...');
    }
    let loaderClose = function(){
        unblockUiElement('#form_add_edit_auth');
    }

    processDataJson('POST', urldest, dataSend, loaderCall, loaderClose).then(function(data){
        var rc = data.response_code,
            rmsg = data.response_message,
            rdata = data.response_data;
        if(rc == '00'){
            manipulateModalBodyDetail(rdata, rmsg, 'addedit');
            $('#modal_add_edit_auth').modal('hide');
            $('#modal_detail').modal({
                backdrop: "static"
            });

            dtTable.ajax.reload( null, false );
        }else{
            alertWarning(rmsg);
        }
    });

    return false;
}

function manipulateModalBodyDetail(rdata, rmsg, modul){
  let alertSccs = '<div class="alert alert-success">'+rmsg+'</div>';
  let dataAdd   = '';

  if(modul == 'reset' || modul == 'addedit'){
      dataAdd = '<tr>'+
                    '<td>Client Secret Text</td>'+
                    '<td>:</td>'+
                    '<td class="font-weight-bold">'+rdata.client_secret_plain+'</td>'+
                '</tr>';
  }

  let modalBody = alertSccs +
                  '<div class="table-responsive">'+
                      '<table class="table table-striped table-sm">'+
                          '<tbody>'+
                              '<tr>'+
                                  '<td>Client ID</td>'+
                                  '<td>:</td>'+
                                  '<td>'+rdata.client_id+'</td>'+
                              '</tr>'+
                              '<tr>'+
                                  '<td>Client Type</td>'+
                                  '<td>:</td>'+
                                  '<td>'+rdata.client_type_desk+'</td>'+
                              '</tr>'+
                              '<tr>'+
                                  '<td>Token Type</td>'+
                                  '<td>:</td>'+
                                  '<td>'+rdata.token_type+'</td>'+
                              '</tr>'+
                              '<tr>'+
                                  '<td>Token Expired</td>'+
                                  '<td>:</td>'+
                                  '<td>'+rdata.token_expired+' Detik</td>'+
                              '</tr>'+
                              '<tr>'+
                                  '<td>Scope</td>'+
                                  '<td>:</td>'+
                                  '<td>'+rdata.scope+'</td>'+
                              '</tr>'+
                              '<tr>'+
                                  '<td>Grant Type</td>'+
                                  '<td>:</td>'+
                                  '<td>'+rdata.grant_type+'</td>'+
                              '</tr>'+
                              dataAdd +
                              '<tr>'+
                                  '<td>Client Secret</td>'+
                                  '<td>:</td>'+
                                  '<td class="font-weight-bold">'+rdata.client_secret+'</td>'+
                              '</tr>'+
                          '</tbody>'+
                      '</table>'+
                  '</div>';

    $('#modal_detail_body').html(modalBody);
}

function manipulateCheckBox(idTr){
    let dataId = $('#'+idTr).attr('data-dataid');
    if($('#checkbox-'+dataId).is(":checked")){
        $('#'+idTr).removeClass('bg-light');
        $('#checkbox-'+dataId).prop('checked', false);
    }else{
        $('#'+idTr).addClass('bg-light');
        $('#checkbox-'+dataId).prop('checked', true);
    }
}
