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

    function RoleFormCtrl($state, $stateParams, roleService, translateService) {
        var vm = this;
        vm.translate = translateService;
        vm.role = {};
        vm.roleId = $stateParams.id;
        vm.isEditMode = vm.roleId;


        vm.save = function save() {
            var promise;
            if (vm.isEditMode) {
                promise = roleService.editRole(vm.role);
            } else {
                promise = roleService.createRole(vm.role);
            }

            promise
                .then(function (result) {
                    $state.go('roles');
                })
                .catch(function (response) {
                    var error = response.data;
                    vm.validationErrors = [];
                    if (error && angular.isObject(error)) {
                        for (var key in error) {
                            vm.validationErrors.push(error[key][0]);
                        }
                    } else { 
                        vm.validationErrors.push(translateService.get('Could not add role.'));
                    }
                });
        };

        function init() {
            if (vm.isEditMode) {
                roleService.getRole(vm.roleId).then(function (result) {
                    vm.role = result.data;
                });
            }
        }

        init();
    }
})();
