'user strict';

angular.module('roles.controllers.main', [
    'system'
])
    .controller('RoleMainController', [
        '$scope',
        '$location',
        '$route',
        'System',
        'RoleService',
        function ($scope, $location, $route, System, RoleService) {

            $(".tooltip").tooltip();

            /**
            *@method refresh
            *@description Load roles list.
            */
            $scope.refresh = function() {
                RoleService.all().then(function(response) {
                    $scope.roles = response;
                });
            };

            /*
             *@method create
             *@description Create new role.
            */
            $scope.create = function() {
                RoleService.create($scope.role).then(function (response) {
                    if (response.Error) {
                        System.Message.error($scope.$resource('roles.role_exists'));
                    } else {
                        $scope.roles.push({Role:$scope.role, Users:0});
                        System.Message.success($scope.$resource('roles.role_created'));
                    }
                });
            };
            
            /*
            *@method remove
            *@param role Role name.
            *@param index Role index in list.
            *@description Remove role.
            */
            $scope.remove = function (role, index) {
                var canDelete = confirm($scope.$resource('utility.areYouShure'));
                if (canDelete) {
                    RoleService.remove(role.Role).then(function (response) {
                        if (response.Error) {
                            System.Message.error(response.Message);
                        } else {
                            $scope.roles.splice(index, 1);
                            System.Message.success($scope.$resource('utility.deleted'));
                        }
                    });
                }
            };

            $scope.refresh();
        }
    ]);
