

var url = '';
var actionUrl = '';

function addNewModel(createUrl,storeUrl) {
    $.get(createUrl,function(data){
        document.getElementById('modal-body').innerHTML = data;
        actionUrl = storeUrl;
    });
}
function editModel(modelEditUrl,updateUrl) {
    $.get(modelEditUrl,function(data){
        document.getElementById('modal-body').innerHTML = data;
        actionUrl = updateUrl;
    });
}
function deleteModel(id,modelDeleteUrl){
    const swalWithBootstrapButtons = Swal.mixin({
        customClass: {
            confirmButton: 'btn btn-success',
            cancelButton: 'btn btn-danger'
        },
        buttonsStyling: false
    });

    swalWithBootstrapButtons.fire({
        title: 'Are you sure?',
        text: "You won't be able to revert this!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Yes, delete it!',
        cancelButtonText: 'No, cancel!',
        reverseButtons: true
    }).then((result) => {
        if (result.isConfirmed) {
        $.ajax({
            url: modelDeleteUrl,
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'DELETE',
            // data: {'_method':'DELETE'},
            success: function (response) {
                swalWithBootstrapButtons.fire(
                    'Deleted!',
                    'Your file has been deleted.',
                    'success'
                )
                $('#row_'+id).addClass('deleteClass');
                $('#row_'+id).fadeOut(5000);
            },
            error: function (response) {
                // handle error response
                showNotification('alert-danger', 'error in deleting process', 'top', 'right', 'animated fadeInRight', 'animated fadeOutRight');
            },
            contentType: false,
            processData: false
        });
        } else if (
            /* Read more about handling dismissals below */
            result.dismiss === Swal.DismissReason.cancel) {
                swalWithBootstrapButtons.fire(
                    'Cancelled',
                    'Your data is safe :)',
                    'error'
                )
            }
    });
    // $.get(modelDeleteUrl,function(data){
    //     document.getElementById('modal-body').innerHTML = data;
    // });
}
function saveData() {
    var formData = new FormData(document.querySelector("form"));
    // console.log(formData);
    // build the ajax call
    $.ajax({
        url: actionUrl,
        type: 'POST',
        data: formData,
        success: function (response) {
            // handle success response
            // console.log(response);
            var parent = document.querySelector('tbody');
            var updated_row = document.getElementById('row_'+response.id);
            if(updated_row){
                parent.removeChild(updated_row);
            }
            parent.insertAdjacentHTML('afterbegin',response.row);

            document.querySelector('.modal-footer').children[1].click();
            showNotification(response.type, response.msg, 'top', 'right', 'animated fadeInRight', 'animated fadeOutRight');

            // document.querySelector('input[name="' + x + '[]"]').parentElement.insertAdjacentHTML('beforeEnd',
            //     '<span class="helper-text" style="color:red;">' +
            //     response.responseJSON.errors[x][y] + '</span><br>'
            // );
        },
        error: function (response) {
            // handle error response
            var errorMessages = document.getElementsByClassName('helper-text');
            // console.log(errorMessages);
            if(errorMessages.length) {
                for (let x in errorMessages) {
                    console.log(x==0,parseInt(x),x);
                    if(x==0||parseInt(x)){
                        errorMessages[x].parentElement.removeChild(errorMessages[x])
                    }
                }
            }
            for(let x in response.responseJSON.errors){
                console.log(response.responseJSON.errors);
                if(x=='files'){
                    // console.log(document.querySelector('input[name="' + x + '[]"]'),x);
                    document.querySelector('input[name="files[]"]').classList.add('invalid');
                    for (let y in response.responseJSON.errors[x]) {
                        document.querySelector('input[name="files[]"]').parentElement.insertAdjacentHTML('beforeEnd',
                            '<span class="helper-text" style="color:red;display:block;">' +
                            response.responseJSON.errors[x][y] + '</span><br>'
                        );
                    }
                }else if(x.substr('0','5')=='files'){
                    document.querySelector('input[name="files[]"]').classList.add('invalid');
                    for (let y in response.responseJSON.errors[x]) {
                        document.querySelector('input[name="files[]"]').parentElement.insertAdjacentHTML('beforeEnd',
                            '<span class="helper-text" style="color:red;display:block;">' +
                            response.responseJSON.errors[x][y] + '</span>'
                        );
                    }
                }else{
                    document.querySelector('input[name="' + x + '"]').classList.add('invalid');
                    for (let y in response.responseJSON.errors[x]) {
                        document.querySelector('input[name="' + x + '"]').parentElement.insertAdjacentHTML('beforeEnd',
                            '<span class="helper-text" data-error="' + response.responseJSON.errors[x][y] + '" style="color:red;display:block;"></span>'
                        );
                    }
                }
            }
        },
        contentType: false,
        processData: false
    });
}
function showNotification(colorName, text, placementFrom, placementAlign, animateEnter, animateExit) {
    if (colorName === null || colorName === '') { colorName = 'bg-black'; }
    if (text === null || text === '') { text = 'Turning standard Bootstrap alerts'; }
    if (animateEnter === null || animateEnter === '') { animateEnter = 'animated fadeInDown'; }
    if (animateExit === null || animateExit === '') { animateExit = 'animated fadeOutUp'; }
    var allowDismiss = true;

    $.notify({
            message: text
        },
        {
            type: colorName,
            allow_dismiss: allowDismiss,
            newest_on_top: true,
            timer: 1000,
            placement: {
                from: placementFrom,
                align: placementAlign
            },
            animate: {
                enter: animateEnter,
                exit: animateExit
            },
            template: '<div data-notify="container" class="bootstrap-notify-container alert alert-dismissible {0} ' + (allowDismiss ? "p-r-35" : "") + '" role="alert">' +
            '<button type="button" aria-hidden="true" class="close" data-notify="dismiss">×</button>' +
            '<span data-notify="icon"></span> ' +
            '<span data-notify="title">{1}</span> ' +
            '<span data-notify="message">{2}</span>' +
            '<div class="progress" data-notify="progressbar">' +
            '<div class="progress-bar progress-bar-{0}" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"></div>' +
            '</div>' +
            '<a href="{3}" target="{4}" data-notify="url"></a>' +
            '</div>'
        });
}

function getBrandModels(obj) {
    $.get('/BrandModels/'+obj.value,function(data){
        document.getElementById('car_model_id').innerHTML = data;
        // console.log(data);
    });
}
