(function () {
    global.dashModule
        .directive('showEditUsers', showEditUsersDirective)
        .controller('showEditUsersCtrl', ['$scope', '$', '$http', '$translate', 'utilsService', showEditUsersCtrl]);

    function showEditUsersDirective() {
        return {
            restrict: 'E',
            templateUrl: 'users/html/showEditUsersTemplate'
        };
    }

    function showEditUsersCtrl($scope, $, $http, $translate, utilsService) {
        $scope.getUsers = getUsers;
        $scope.generateTokenForUserPassword = generateTokenForUserPassword;
        $scope.showHideDialog = showHideDialog;
        $scope.isDialogVisible = false;
        $scope.users = [];

        function getUsers() {
            $http({
                method: 'GET',
                url: 'users/api/getUsers'
            }).then(showUsers, utilsService.onHttpError);
        }

        function showUsers(response) {
            if(response.data) {
                $scope.users = response.data;
            }
        }

        function generateTokenForUserPassword(userInfo) {
            const params = $.param({
                userInfo: JSON.stringify(userInfo)
            });
            $http({
                method: 'POST',
                data: params,
                url: 'utils/api/generateTokenForUserPassword'
            }).then(showConfirmationMessage, utilsService.onHttpError);
        }

        function showConfirmationMessage(response) {
            if (response.data && response.data.messages) {
                response.data.messages.forEach(messageData => {
                    const message = $translate.instant('users.forms.messages.' + messageData.message);
                    utilsService.displayMessage(messageData.code, message);
                });
            }
        }

        function showHideDialog(userInfo = '') {
            $scope.userSelected = userInfo;
            $scope.$evalAsync(() => {
                $scope.isDialogVisible = !$scope.isDialogVisible;
            });
        }
    }

})();
