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 propertyTypesScript = propertyTypesScript || function () {
    var isInit = false;
    var propertyTypeListingDataTable = null;
    var selectedPropertyTypes = [];

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

    var handler = function () {
        propertyTypeListDataTable();
        globalScript.initValidator();
        initEditor();

        $("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('.propertyType-id').val();
                    if (selectedPropertyTypes.indexOf(roleId) === -1) {
                        selectedPropertyTypes.push(roleId);
                    }
                });
            } else {
                $(".bulkRow, .select_all").prop('checked', false);
                $('#bulk-action-checkbox').prop('checked', false);
                selectedPropertyTypes = [];
            }
        });

        $('body').on('click', '.bulkRow', function () {
            var status = this.checked;
            var roleId = $(this).closest('tr').find('.propertyType-id').val();
            if (status === true) {
                if (selectedPropertyTypes.indexOf(roleId) === -1) {
                    selectedPropertyTypes.push(roleId);
                }
                $('#bulk-action-checkbox').prop('checked', true);
            } else {
                selectedPropertyTypes.remove(roleId);
            }
            if (selectedPropertyTypes.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 (selectedPropertyTypes.length === 0) {
                    $('#bulk_actions_error').html('Please select propertyType(s) first').show();
                } else {
                    $('#bulk_actions_error').hide();
                    if (bulkOption === 'delete_bulk') {
                        globalScript.showConfirmationAlert(
                            'You want to delete selected propertyType(s)?',
                            function () {
                                deletePropertyTypes(function () {
                                    toastr.success('PropertyType(s) deleted successfully');
                                    propertyTypeListDataTable();
                                    $(".bulkRow, .select_all").prop('checked', false);
                                });
                            }
                        )
                    }
                }
            }
        });

        $('body').on('submit', '#create_propertyType_form', function (e) {
            e.preventDefault();
            if ($('#submit_btn').hasClass('disabled')) {
                return false;
            }
            $('#submit_btn').addClass('disabled');
            $('.add_errors').hide();
            $('.add_errors ul').html('');
            var propertyType_name = $('#propertyType_name').val();
            var propertyType_parent = $('#propertyType_parent').val();
            var propertyType_meta_title = $('#propertyType_meta_title').val();
            var propertyType_meta_keywords = $('#propertyType_meta_keywords').val();
            var propertyType_meta_description = $('#propertyType_meta_description').val();
            var propertyType_full_description = $('#propertyType_full_description').summernote('code');
            var obj = Object.create(globalScript.CREATE_ATTRIBUTE);
            obj.data = {
                'type': 'propertyType',
                'parent_id': propertyType_parent,
                'name': propertyType_name,
                'full_desc': propertyType_full_description,
                'meta_title': propertyType_meta_title,
                'meta_keywords': propertyType_meta_keywords,
                'meta_desc': propertyType_meta_description,
            };
            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)
                    // $('#addPropertyTypeModal').modal('hide');
                    // propertyTypeListDataTable();
                }
            });
        });

        $('body').on('submit', '#edit_propertyType_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 propertyTypeId = $('#propertyType_id').val();
            var propertyType_name = $('#edit_propertyType_name').val();
            var edit_propertyType_parent = $('#edit_propertyType_parent').val();
            var propertyType_meta_title = $('#edit_propertyType_meta_title').val();
            var propertyType_meta_keywords = $('#edit_propertyType_meta_keywords').val();
            var propertyType_meta_description = $('#edit_propertyType_meta_description').val();
            var propertyType_full_description = $('#edit_propertyType_full_description').summernote('code');
            var obj = Object.create(globalScript.UPDATE_ATTRIBUTE);
            obj.url = obj.url(propertyTypeId);
            obj.data = {
                'name': propertyType_name,
                'parent_id': edit_propertyType_parent,
                'full_desc': propertyType_full_description,
                'meta_title': propertyType_meta_title,
                'meta_keywords': propertyType_meta_keywords,
                'meta_desc': propertyType_meta_description,
            };
            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)
                    // $('#editPropertyTypeModal').modal('hide');
                    // propertyTypeListDataTable();
                }
            });
        });

        $('body').on('click', '.edit-btn', function () {
            var propertyTypeId = $(this).closest('tr').find('.propertyType-id').val();
            var obj = Object.create(globalScript.GET_ATTRIBUTE_DETAILS);
            var url = obj.url(propertyTypeId);
            obj.url = url;
            globalScript.ajaxCall(obj).done(function (response) {
                if (response.hasOwnProperty('_metadata') && response._metadata.hasOwnProperty('outcomeCode') && response._metadata.outcomeCode === 0) {
                    $('body').find('#propertyType_id').val(response.records.id);
                    $('body').find('#edit_propertyType_form #edit_propertyType_name').val(response.records.name);
                    $('body').find('#edit_propertyType_form #edit_propertyType_parent').val(response.records.parent_id);
                    $('body').find('#edit_propertyType_form #edit_propertyType_meta_title').val(response.records.meta_title);
                    $('body').find('#edit_propertyType_form #edit_propertyType_meta_keywords').val(response.records.meta_keywords);
                    $('body').find('#edit_propertyType_form #edit_propertyType_meta_description').val(response.records.meta_desc);
                    $('body').find('#edit_propertyType_form #edit_propertyType_full_description').summernote("code", response.records.full_desc);
                    $('.edit_errors').hide();
                    $('.edit_errors ul').html('');
                    $('#editPropertyTypeModal').modal('show');
                }
            })
        });

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

        $('#addPropertyTypeModal').on('hidden.bs.modal', function (e) {
            $('.add_errors').hide();
            $('.add_errors ul').html('');
            $('#create_propertyType_form').trigger("reset");
            $('#propertyType_full_description').summernote('reset');
        });

        $('#editPropertyTypeModal').on('hidden.bs.modal', function (e) {
            $('.edit_errors').hide();
            $('.edit_errors ul').html('');
            $('#edit_propertyType_form').trigger("reset");
            $('#edit_propertyType_full_description').summernote('reset');
        });
    };

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

    var propertyTypeListDataTable = function () {
        if (propertyTypeListingDataTable != null) {
            propertyTypeListingDataTable.clear().destroy();
        }
        propertyTypeListingDataTable = $('#propertyTypesListTable').DataTable({
            "ajax": {
                url: globalScript.APP_URL + "attributes?type=propertyType",
                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": "Title",
                    "name": "name",
                    "searchable": true,
                    "orderable": true
                },
                {
                    "data": "parent",
                    "title": "Parent",
                    "name": "parent.name",
                    "searchable": false,
                    "orderable": false
                },
                {
                    "data": null,
                    "title": "Actions",
                    "searchable": false,
                    "orderable": false
                }
            ],
            "order": [[0, 'desc']],
            "rowCallback": function (row, data) {
                var tmpl = _.template($('#propertyTypesListTemplate').html());
                $(row).html(tmpl(data));
            }
        });
    };

    var initEditor = function () {
        $('.content_area').summernote({
            onCreateLink: function (originalLink) {
                return originalLink; // return original link
            },
            dialogsInBody: true,
            height: 300,
            tabsize: 2
        });
    };

    return {
        'init': init
    }

}();

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