/*global angular*/
(function () {
    angular
        .module('simplAdmin.core')
        .controller('RoleListCtrl', ['roleService', 'translateService', RoleListCtrl]);

    function RoleListCtrl(roleService, translateService) {
        var vm = this;
        vm.tableStateRef = {};
        vm.roles = [];
        vm.translate = translateService;

        vm.getRoles = function getRoles(tableState) {
            vm.tableStateRef = tableState;
            vm.isLoading = true;
            roleService.getRoles(tableState).then(function (result) {
                vm.roles = result.data.items;
                tableState.pagination.numberOfPages = result.data.numberOfPages;
                tableState.pagination.totalItemCount = result.data.totalRecord;
                vm.isLoading = false;
            });
        };

        vm.update = function (role) {
            roleService.editRole(role)
                .then(function (result) {
                    toastr.success(role.name + ' has been updated');
                })
                .catch(function (response) {
                    toastr.error(response.data.error);
                });
        };

        vm.deleteRole = function (role) {
            bootbox.confirm('Are you sure you want to delete this role: ' + simplUtil.escapeHtml(role.name), function (result) {
                if (result) {
                    roleService.deleteRole(role)
                        .then(function (result) {
                            vm.getRoles(vm.tableStateRef);
                            toastr.success(role.name + ' has been deleted');
                        })
                        .catch(function (response) {
                            toastr.error(response.data.error);
                        });
                }
            });
        };
    }
})();
