(function () {
    global.dashModule
        .directive('changePassword', changePasswordDirective)
        .controller('changePasswordCtrl', ['$scope', '$', '$http', '$translate', 'utilsService', changePasswordCtrl]);

    function changePasswordDirective() {
        return {
            restrict: 'E',
            templateUrl: 'profileSettings/html/ChangePasswordTemplate'
        };
    }

    function changePasswordCtrl($scope, $, $http, $translate, utilsService) {
        $scope.changePassword = changePassword;
        $scope.showHideDialog = showHideDialog;
        $scope.isDialogVisible = false;

        function changePassword() {
            const params = $.param({
                passwords: JSON.stringify($scope.data)
            });

            $http({
                method: 'POST',
                data: params,
                url: 'utils/api/changePassword'
            }).then(showConfirmationMessage, utilsService.onHttpError);
        }

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

                    if(messageData.code === 'success') {
                        $scope.data = {};
                    }
                });
            }
        }

        function showHideDialog() {
            if($scope.data && Object.keys($scope.data).length === 3) {
                $scope.$evalAsync(() => {
                    $scope.isDialogVisible = !$scope.isDialogVisible;
                });
            }
        }
    }
})();
