$(function () {
    baseUrl = $('#base_url').val();

    $('#form_login').submit(function(){
        var form = $(this);
        if (form[0].checkValidity() === false) {
            form.addClass('was-validated'); return false;
        }

        $.ajax({
            url: baseUrl + 'login/doLoginJson',
            type: 'POST',
            dataType: 'json',
            data: $(this).serialize(),
            beforeSend: function(){
                blockUiElement('#card_login', 'Memproses login...');
            },
            success: function(r){
                let rc = r.response_code,
                    rmsg = r.response_message;
                if(rc == '00'){
                    window.open(baseUrl + 'home', '_self');
                }else{
                    alertWarning(rmsg);
                }
            },
            complete: function(){
                unblockUiElement('#card_login');
            },
            error: function(jqXHR, exception){
                let msgErr = getMessageAjaxError(jqXHR, exception);
                alertError(msgErr);
            }
        });

        return false;
    });
});

function alertWarning(message, callbackFunc){
    Swal.fire({
        type: 'warning',
        title: 'Peringatan...',
        text: message,
    }).then((result) => {
        if( typeof(callback) == 'function'){
            callbackFunc();
        }
    });
}

function alertError(message, callback){
    Swal.fire({
        type: 'error',
        title: 'Error...',
        text: message,
    }).then((result) => {
        if( typeof(callback) == 'function'){
            callbackFunc();
        }
    });
}

function getMessageAjaxError(jqXHR, exception){
    if (jqXHR.status === 0) {
        return 'Not connect.\n Verify Network.';
    }
    if (jqXHR.status == 404) {
        return 'Requested page not found. [404]';
    }
    if (jqXHR.status == 500) {
        return 'Internal Server Error [500].';
    }
    if (exception === 'parsererror') {
        return 'Requested JSON parse failed.';
    }
    if (exception === 'timeout') {
        return 'Time out error.';
    }
    if (exception === 'abort') {
        return 'Ajax request aborted.';
    }

    return 'Uncaught Error.\n' + jqXHR.responseText;
}

function blockUiElement(elem, text){
    $(elem).block({
        message: '<i class="fa fa-spinner fa-spin"></i> ' + text,
        css: {
            padding:        0,
            margin:         0,
            width:          '100%',
            top:            '40%',
            left:           '35%',
            textAlign:      'center',
            color:          '#000',
            border:         '0px',
            backgroundColor:'transaparent',
            cursor:         'wait'
        },
        overlayCSS:  {
            backgroundColor: '#fff',
            opacity: 0.6,
            cursor: 'wait'
        }
    });
}
function unblockUiElement(elem){
    $(elem).unblock();
}
