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 adminsScript = adminsScript || function () {
    var isInit = false;
    var adminListingDataTable = null;
    var adminRolesListingDataTable = null;
    var selectedAdmins = [];
    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 () {
        adminListDataTable();
        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('.admin-id').val();
                    if (selectedAdmins.indexOf(roleId) === -1) {
                        selectedAdmins.push(roleId);
                    }
                });
            } else {
                $(".bulkRow, .select_all").prop('checked', false);
                $('#bulk-action-checkbox').prop('checked', false);
                selectedAdmins = [];
            }
        });

        $('body').on('click', '.bulkRow', function () {
            var status = this.checked;
            var roleId = $(this).closest('tr').find('.admin-id').val();
            if (status === true) {
                if (selectedAdmins.indexOf(roleId) === -1) {
                    selectedAdmins.push(roleId);
                }
                $('#bulk-action-checkbox').prop('checked', true);
            } else {
                selectedAdmins.remove(roleId);
            }
            if (selectedAdmins.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 (selectedAdmins.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 () {
                                deleteAdmins(function () {
                                    toastr.success('Admin(s) deleted successfully');
                                    adminListDataTable();
                                    $(".bulkRow, .select_all").prop('checked', false);
                                });
                            }
                        )
                    }
                }
            }
        });

        $('body').on('submit', '#create_admin_form', function (e) {
            e.preventDefault();
            if ($('#submit_btn').hasClass('disabled')) {
                return false;
            }
            $('#submit_btn').addClass('disabled');
            $('.add_errors').hide();
            $('.add_errors ul').html('');
            var adminName = $('#admin_name').val();
            var adminEmail = $('#admin_email').val();
            var adminPassword = $('#admin_password').val();
            var obj = Object.create(globalScript.CREATE_ADMIN);
            obj.data = {
                'name': adminName,
                'email': adminEmail,
                'password': adminPassword
            };
            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);
                    $('#addAdminModal').modal('hide');
                    $('#create_admin_form').trigger("reset");
                    adminListDataTable();
                }
            });
        });

        $('body').on('change', '.update_user_status', function () {
            var status = $(this).val();
            var adminId = $(this).closest('tr').find('.admin-id').val();
            selectedAdmins.push(adminId);
            updateUserStatus(status, function () {
                toastr.success('Status successfully updated');
                adminListDataTable();
            });
        });

        $('body').on('submit', '#edit_admin_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 adminId = $('#admin_id').val();
            var adminName = $('#edit_admin_name').val();
            var adminEmail = $('#edit_admin_email').val();
            var adminPassword = $('#edit_admin_password').val();
            var obj = Object.create(globalScript.UPDATE_ADMIN);
            var url = obj.url(adminId);
            obj.url = url;
            obj.data = {
                'name': adminName,
                'email': adminEmail,
                'password': adminPassword,
            };
            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);
                    $('#editAdminModal').modal('hide');
                    $('#edit_admin_form').trigger("reset");
                    adminListDataTable();
                }
            });
        });

        $('body').on('click', '.edit-btn', function () {
            var adminId = $(this).closest('tr').find('.admin-id').val();
            var obj = Object.create(globalScript.GET_ADMIN_DETAILS);
            var url = obj.url(adminId);
            obj.url = url;
            globalScript.ajaxCall(obj).done(function (response) {
                if (response.hasOwnProperty('_metadata') && response._metadata.hasOwnProperty('outcomeCode') && response._metadata.outcomeCode === 0) {
                    $('body').find('#admin_id').val(response.records.id);
                    $('body').find('#edit_admin_form #edit_admin_name').val(response.records.name);
                    $('body').find('#edit_admin_form #edit_admin_email').val(response.records.email);
                    $('.edit_errors').hide();
                    $('.edit_errors ul').html('');
                    $('#editAdminModal').modal('show');
                }
            })
        });

        $('body').on('click', '.roles-btn', function () {
            var adminId = $(this).closest('tr').find('.admin-id').val();
            $('.admin_main_id').val(adminId);
            $('#rolesListModal').modal('show');
            adminRolesListDataTable(adminId);
        });

        $('body').on('click', '#show_role_form', function () {
            $('#roles_list').html('');
            getAdminRolesListExcept(function () {
                $('#add_role_to_admin_form').show();
                $('#roles_list').selectpicker('val', '');
                $('#roles_list').selectpicker('refresh');
                globalScript.initValidatorSimple();
            });


        });

        $('body').on('submit', '#add_role_to_admin_form', function (e) {
            e.preventDefault();
            if ($('#roles_btn').hasClass('disabled')) {
                return false;
            }
            $('#roles_btn').addClass('disabled');
            $('.roles_errors').hide();
            $('.roles_errors ul').html('');
            var adminId = $('.admin_main_id').val();
            var roleIds = $('#roles_list').val();
            var obj = Object.create(globalScript.ASSIGN_ROLES_TO_ADMIN);
            obj.data = {
                'role_ids': roleIds,
                'admin_id': adminId
            };

            globalScript.ajaxCall(obj).done(function (response) {
                if (response.errors && response.errors.length !== 0) {
                    $('#roles_btn').removeClass('disabled');
                    _.each(response.errors, function (v, k) {
                        $('.roles_errors ul').append('<li>' + v + '</li>');
                        $('.roles_errors').show();
                    });
                } else {
                    if (response.hasOwnProperty('_metadata') && response._metadata.hasOwnProperty('outcomeCode') && response._metadata.outcomeCode === 0) {
                        adminRolesListDataTable(adminId);
                        toastr.success(response._metadata.message);
                        $('#roles_list').html('');
                        $('#add_role_to_admin_form').hide();
                    }
                }
            });
        });

        $('body').on('click', '.delete_admin_roles_btn', function () {
            var adminId = $('.admin_main_id').val();
            var roleId = $(this).closest('tr').find('.admin-role-id').val();
            var obj = Object.create(globalScript.REMOVE_ROLE_FROM_ADMIN);
            obj.data = {
                'admin_id': adminId,
                'role_id': roleId
            };
            globalScript.ajaxCall(obj).done(function (response) {
                if (response.hasOwnProperty('_metadata') && response._metadata.hasOwnProperty('outcomeCode') && response._metadata.outcomeCode === 0) {
                    toastr.success(response._metadata.message);
                    $('#roles_list').html('');
                    $('#add_role_to_admin_form').hide();
                    adminRolesListDataTable(adminId);
                }
            })
        });

        $('body').on('click', '#remove_all_attach_roles_btn', function () {
            var adminId = $('.admin_main_id').val();
            var obj = Object.create(globalScript.REMOVE_ALL_ROLES_FROM_ADMIN);
            obj.data = {
                'admin_id': adminId
            };
            globalScript.showConfirmationAlert(
                'You want to remove all roles from this admin?',
                function () {
                    globalScript.ajaxCall(obj).done(function (response) {
                        if (response.hasOwnProperty('_metadata') && response._metadata.hasOwnProperty('outcomeCode') && response._metadata.outcomeCode === 0) {
                            toastr.success(response._metadata.message);
                            $('#roles_list').html('');
                            $('#add_role_to_admin_form').hide();
                            adminRolesListDataTable(adminId);
                        }
                    })
                }
            )
        });

        $('body').on('click', '.delete-btn', function () {
            selectedAdmins = [];
            $(".bulkRow, .select_all").prop('checked', false);
            var adminId = $(this).closest('tr').find('.admin-id').val();
            selectedAdmins.push(adminId);
            globalScript.showConfirmationAlert(
                'You want to delete selected admin?',
                function () {
                    deleteAdmins(function () {
                        toastr.success('Admin deleted successfully');
                        $("#profileModal").modal("hide");
                        adminListDataTable();
                    });
                }
            )
        });

        $('body').on('click', '.email-btn', function () {
            var email = $(this).closest('tr').find('.admin-id').attr('data-pro-email');
            $("#reply_email").val(email);
            $('#profileModal').modal('hide');
            setTimeout(function () {
                $('#emailModal').modal('show');
            }, 500);
        });

        $('body').on('submit', '#create_reply_form', function (e) {
            e.preventDefault();
            if ($('#reply_btn').hasClass('disabled')) {
                return false;
            }
            $('.reply_errors').hide();
            $('.reply_errors ul').html('');
            var replyEmail = $('#reply_email').val();
            var replySubject = $('#reply_subject').val();
            var replyContent = $('#reply_content').summernote('code');
            var obj = Object.create(globalScript.EMAIL_ADMIN);
            obj.data = {
                'email': replyEmail,
                'subject': replySubject,
                'body': replyContent
            };
            globalScript.ajaxCall(obj).done(function (response) {
                if (response.errors && response.errors.length !== 0) {
                    $('.reply_errors').show();
                    _.each(response.errors, function (v, k) {
                        $('.reply_errors ul').append('<li>' + v + '</li>');
                    });
                    return false;
                } else if (response.hasOwnProperty('_metadata') && response._metadata.hasOwnProperty('outcomeCode') && response._metadata.outcomeCode === 0) {
                    toastr.success(response._metadata.message);
                    $('#emailModal').modal('hide');
                    setTimeout(function () {
                        $('#profileModal').modal('show');
                    }, 500);
                }
            });
        });

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

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

        $('#rolesListModal').on('hidden.bs.modal', function (e) {
            $('.admin_main_id').val('');
            $('#roles_list').html('');
            $('#add_role_to_admin_form').hide();
            $('.roles_errors').hide();
            $('.roles_errors ul').html('');
            adminListDataTable();
        });

        $('#emailModal').on('hidden.bs.modal', function (e) {
            $('#reply_content').summernote('reset');
            $('#reply_subject').val('');
            $('#emailModal').modal('hide');
            setTimeout(function () {
                $('#profileModal').modal('show');
            }, 500);
        });
    };

    var getAdminRolesListExcept = function (callback) {
        var adminId = $('.admin_main_id').val();
        var obj = Object.create(globalScript.GET_ADMIN_ROLES_EXCEPT);
        var url = obj.url(adminId);
        obj.url = url;
        globalScript.ajaxCall(obj).done(function (response) {
            if (response.hasOwnProperty('_metadata') && response._metadata.hasOwnProperty('outcomeCode') && response._metadata.outcomeCode === 0) {
                if (response.records.adminRolesList === null) {
                    toastr.error('No role found');
                } else if (response.records.adminRolesList.length !== 0) {
                    _.each(response.records.adminRolesList, function (v, k) {
                        $('#roles_list').append('<option value="' + v.id + '">' + v.display_name + '</option>');
                    });
                    if (typeof callback == 'function') callback();
                } else {
                    toastr.success('This admin already have all roles');
                }
            }
        })
    };

    var deleteAdmins = function (callback) {
        var obj = Object.create(globalScript.DELETE_ADMIN);
        obj.data = {
            'admin_ids[]': selectedAdmins
        };
        globalScript.ajaxCall(obj).done(function (response) {
            selectedAdmins = [];
            if (typeof callback == 'function') callback();
        });
    };

    var adminListDataTable = function () {
        if (adminListingDataTable != null) {
            adminListingDataTable.clear().destroy();
        }
        adminListingDataTable = $('#adminsListTable').DataTable({
            "ajax": {
                url: globalScript.APP_URL + "admins",
                type: "GET",
                xhrFields: {
                    withCredentials: true
                },
                dataSrc: function (json) { // Manipulate the data returned from the server
                    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": "First Name",
                    "name": "name",
                    "searchable": true,
                    "orderable": true
                },
                {"data": "email", "title": "Email", "name": "email", "searchable": true, "orderable": true},
                {"data": "status", "title": "Status", "name": "status", "searchable": false, "orderable": false},
                {"data": "last_login", "title": "Last login", "name": "last_login", "searchable": false, "orderable": true},
                {
                    "data": null,
                    "title": "Action",
                    "searchable": false,
                    "orderable": false
                }
            ],
            "order": [[0, 'desc']],
            "rowCallback": function (row, data) {
                var tmpl = _.template($('#adminsListTemplate').html());
                $(row).html(tmpl(data));
            }
        });
    };

    var adminRolesListDataTable = function (adminId) {
        if (adminRolesListingDataTable != null) {
            adminRolesListingDataTable.clear().destroy();
        }
        adminRolesListingDataTable = $('#adminRolesListTable').DataTable({
            "ajax": {
                url: globalScript.APP_URL + "getadminroles/" + adminId,
                type: "GET",
                xhrFields: {
                    withCredentials: true
                },
                dataSrc: function (json) { // Manipulate the data returned from the server
                    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;
                    if (json.records.data.length !== 0) {
                        $("body").find(".attach_modal_footer").show();
                    } else {
                        $("body").find(".attach_modal_footer").hide();
                    }
                    return json.records.data;
                }
            },
            "searching": true,
            "ordering": false,
            "serverSide": true,
            "paging": true,
            "columns": [
                {
                    "data": 'display_name',
                    'title': 'Title',
                    "name": 'display_name',
                    "searchable": true,
                    "orderable": true,
                    "visible": true
                },
                {
                    "data": null,
                    'title': 'Action',
                    "searchable": false,
                    "orderable": false,
                    "visible": true
                }
            ],
            "rowCallback": function (row, data) {
                var tmpl = _.template($('#adminRolesListTemplate').html());
                $(row).html(tmpl(data));
            }
        });
    };

    var updateUserStatus = function (status, callback) {
        var obj = Object.create(globalScript.UPDATE_USER_STATUS);
        obj.data = {
            'user_ids[]': selectedAdmins,
            'status': status
        };
        globalScript.ajaxCall(obj).done(function (response) {
            selectedAdmins = [];
            if (typeof callback == 'function') callback();
        });
    };

    return {
        'init': init
    }

}();

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