Array.prototype.remove = function () {
    var what, a = arguments, L = a.length, ax;
    while (L && this.length) {
        what = a[--L];
        while ((ax = this.indexOf(what)) !== -1) {
            this.splice(ax, 1);
        }
    }
    return this;
};
var attributesScript = attributesScript || function () {
    var isInit = false;
    var attributeListingDataTable = null;
    var selectedAttributes = [];
    var customCheckBox = '<div class="icheck-material-primary f_custom_checkbox" style="pointer-events: none"><input type="checkbox" id="bulk-action-checkbox" class="select_all" /><label for="bulk-action-checkbox"></label></div>';

    var init = function () {
        if (isInit) return;
        isInit = true;
        handler();
    };

    var handler = function () {
        attributeListDataTable();
        globalScript.initValidator();

        $("body").on('click', '.select_all', function () { // bulk checked
            var status = this.checked;
            if (status === true) {
                $('#bulk-action-checkbox').prop('checked', true);
                $('body').find(".bulkRow").each(function () {
                    $(this).prop("checked", status);
                    var roleId = $(this).closest('tr').find('.attribute-id').val();
                    if (selectedAttributes.indexOf(roleId) === -1) {
                        selectedAttributes.push(roleId);
                    }
                });
            } else {
                $(".bulkRow, .select_all").prop('checked', false);
                $('#bulk-action-checkbox').prop('checked', false);
                selectedAttributes = [];
            }
        });

        $('body').on('click', '.bulkRow', function () {
            var status = this.checked;
            var roleId = $(this).closest('tr').find('.attribute-id').val();
            if (status === true) {
                if (selectedAttributes.indexOf(roleId) === -1) {
                    selectedAttributes.push(roleId);
                }
                $('#bulk-action-checkbox').prop('checked', true);
            } else {
                selectedAttributes.remove(roleId);
            }
            if (selectedAttributes.length === 0) {
                $(".bulkRow, .select_all").prop('checked', false);
            }
        });

        $('body').on('click', '#apply_bulk_actions_btn', function () {
            var bulkOption = $('#bulk_actions').val();
            if (bulkOption === '') {
                $('#bulk_actions_error').html('Please select an action first').show();
            } else {
                if (selectedAttributes.length === 0) {
                    $('#bulk_actions_error').html('Please select admin(s) first').show();
                } else {
                    $('#bulk_actions_error').hide();
                    if (bulkOption === 'delete_bulk') {
                        globalScript.showConfirmationAlert(
                            'You want to delete selected admin(s)?',
                            function () {
                                deleteAttributes(function () {
                                    toastr.success('Admin(s) deleted successfully');
                                    attributeListDataTable();
                                    $(".bulkRow, .select_all").prop('checked', false);
                                });
                            }
                        )
                    }
                }
            }
        });

        $('body').on('submit', '#create_attribute_form', function (e) {
            e.preventDefault();
            if ($('#submit_btn').hasClass('disabled')) {
                return false;
            }
            $('#submit_btn').addClass('disabled');
            $('.add_errors').hide();
            $('.add_errors ul').html('');
            var attrName = $('#attr_name').val();
            var attrParent = $('#attr_parent').val();
            var attrSortOrder = $('#attr_sort_order').val();
            var obj = Object.create(globalScript.CREATE_ATTRIBUTE);
            obj.data = {
                'name': attrName,
                'parent_id': attrParent,
                'sort_order': attrSortOrder
            };
            globalScript.ajaxCall(obj).done(function (response) {
                if (response.errors && response.errors.length !== 0) {
                    $('.add_errors').show();
                    $('#submit_btn').removeClass('disabled');
                    _.each(response.errors, function (v, k) {
                        $('.add_errors ul').append('<li>' + v + '</li>');
                    });
                    return false;
                } else {
                    toastr.success(response._metadata.message);
                    setTimeout(function(){window.location.reload()},500)
                    // $('#addAttributeModal').modal('hide');
                    // $('#create_attribute_form').trigger("reset");
                    // attributeListDataTable();
                }
            });
        });

        $('body').on('submit', '#edit_attribute_form', function (e) {
            e.preventDefault();
            if ($('#edit_submit_btn').hasClass('disabled')) {
                return false;
            }
            $('#edit_submit_btn').addClass('disabled');
            $('.edit_errors').hide();
            $('.edit_errors ul').html('');
            var attrId = $('#attribute_id').val();
            var attrName = $('#edit_attr_name').val();
            var attrParent = $('#edit_attr_parent').val();
            var attrSortOrder = $('#edit_attr_sort_order').val();
            var obj = Object.create(globalScript.UPDATE_ATTRIBUTE);
            obj.url = obj.url(attrId);
            obj.data = {
                'name': attrName,
                'parent_id': attrParent,
                'sort_order': attrSortOrder
            };
            globalScript.ajaxCall(obj).done(function (response) {
                if (response.errors && response.errors.length !== 0) {
                    $('#edit_submit_btn').removeClass('disabled');
                    _.each(response.errors, function (v, k) {
                        $('.edit_errors ul').append('<li>' + v + '</li>');
                        $('.edit_errors').show();
                    });
                } else {
                    toastr.success(response._metadata.message);
                    setTimeout(function(){window.location.reload()},500)
                    // $('#editAttributeModal').modal('hide');
                    // $('#edit_attribute_form').trigger("reset");
                    // attributeListDataTable();
                }
            });
        });

        $('body').on('click', '.edit-btn', function () {
            var attributeId = $(this).closest('tr').find('.attribute-id').val();
            var obj = Object.create(globalScript.GET_ATTRIBUTE_DETAILS);
            var url = obj.url(attributeId);
            obj.url = url;
            globalScript.ajaxCall(obj).done(function (response) {
                if (response.hasOwnProperty('_metadata') && response._metadata.hasOwnProperty('outcomeCode') && response._metadata.outcomeCode === 0) {
                    $('body').find('#attribute_id').val(response.records.id);
                    $('body').find('#edit_attribute_form #edit_attr_name').val(response.records.name);
                    $('body').find('#edit_attribute_form #edit_attr_parent').val(response.records.parent_id);
                    $('.edit_errors').hide();
                    $('.edit_errors ul').html('');
                    $('#editAttributeModal').modal('show');
                }
            })
        });

        $('body').on('click', '.delete-btn', function () {
            selectedAttributes = [];
            $(".bulkRow, .select_all").prop('checked', false);
            var attributeId = $(this).closest('tr').find('.attribute-id').val();
            selectedAttributes.push(attributeId);
            globalScript.showConfirmationAlert(
                'You want to delete?',
                function () {
                    deleteAttributes(function () {
                        toastr.success('Deleted successfully');
                        attributeListDataTable();
                    });
                }
            )
        });

        $('#addAttributeModal').on('hidden.bs.modal', function (e) {
            $('.add_errors').hide();
            $('.add_errors ul').html('');
        });

        $('#editAttributeModal').on('hidden.bs.modal', function (e) {
            $('.edit_errors').hide();
            $('.edit_errors ul').html('');
        });
    };

    var deleteAttributes = function (callback) {
        var obj = Object.create(globalScript.DELETE_ATTRIBUTE);
        obj.data = {
            'attribute_ids[]': selectedAttributes
        };
        globalScript.ajaxCall(obj).done(function (response) {
            selectedAttributes = [];
            if (typeof callback == 'function') callback();
        });
    };

    var attributeListDataTable = function () {
        if (attributeListingDataTable != null) {
            attributeListingDataTable.clear().destroy();
        }
        attributeListingDataTable = $('#attributesListTable').DataTable({
            "ajax": {
                url: globalScript.APP_URL + "attributes",
                type: "GET",
                xhrFields: {
                    withCredentials: true
                },
                dataSrc: function (json) {
                    if (json.hasOwnProperty('_metadata') && json._metadata.hasOwnProperty('outcomeCode') && json._metadata.outcomeCode === 4) {
                        window.top.location.href = "login";
                        return;
                    }
                    json.draw = json.records.draw;
                    json.recordsTotal = json.records.recordsTotal;
                    json.recordsFiltered = json.records.recordsFiltered;
                    $('body').find('#module_total_count').html(json.records.recordsTotal);
                    if (json.records.data.length !== 0) {
                        $("body").find(".f_custom_checkbox").css('pointer-events', 'all');
                        $("body").find(".f_custom_card_footer").show();
                    } else {
                        $("body").find(".f_custom_card_footer").hide();
                    }
                    return json.records.data;
                }
            },
            "searching": true,
            "ordering": true,
            "serverSide": true,
            "paging": true,
            "stateSave": false,
            "columns": [
                {
                    "orderable": true,
                    "searchable": false,
                    "data": 'created_at',
                    "visible": false
                },
                {
                    "data": "name",
                    "title": "Name",
                    "name": "name",
                    "searchable": true,
                    "orderable": true
                },
                {"data": "parent", "title": "parent", "name": "parent.name", "searchable": false, "orderable": false},
                {"data": "added_by", "title": "Added by", "name": "added_by.name", "searchable": false, "orderable": false},
                {
                    "data": null,
                    "title": "Action",
                    "searchable": false,
                    "orderable": false
                }
            ],
            "order": [[0, 'desc']],
            "rowCallback": function (row, data) {
                var tmpl = _.template($('#attributesListTemplate').html());
                $(row).html(tmpl(data));
            }
        });
    };

    return {
        'init': init
    }

}();

$(document).ready(function () {
    attributesScript.init();
});
