backupApp.controller('CreatePasswordController', function($scope, authenticationApiConnector, DialogService, gettextCatalog) {

    const sendPassword = () => {
        saltedpwd =  CryptoJS.lib.WordArray.random(256/8).toString(CryptoJS.enc.Base64);
        serverPassphrase = CryptoJS.SHA256(CryptoJS.enc.Hex.parse(CryptoJS.enc.Utf8.parse($scope.password) + CryptoJS.enc.Base64.parse(saltedpwd))).toString(CryptoJS.enc.Base64);

        const requestBody = {
            'server-passphrase-salt': saltedpwd,
            'server-passphrase': serverPassphrase,
        };

        return authenticationApiConnector.post('./create-password.cgi', requestBody);
    }

    function passwordIsValid () {
        const forbidenChar = /[\(\)\{\}\[\]\|`¬¦!"£\$%\^&\*"<>:;#~_\-\+=,@]/;
        const forbidenFound = $scope.password?.match(forbidenChar);
        $scope.HasForbiddenCharacters = forbidenFound && forbidenFound.length > 0;
        $scope.LengthIsValid = $scope.password?.length >= 8;

        const minimalComplexity = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])/;
        const minimalComplixityFound = $scope.password?.match(minimalComplexity);
        $scope.HasMinimalComplexity = minimalComplixityFound && minimalComplixityFound.length > 0;
        $scope.passwordIsValid = !$scope.HasForbiddenCharacters
            && $scope.LengthIsValid
            && $scope.HasMinimalComplexity
            && $scope.password == $scope.repeatPassword
    }

    $scope.$watch('password', passwordIsValid);
    $scope.$watch('repeatPassword', passwordIsValid);

    $scope.createPassword = function () {    
        if ($scope.processing)
            return;

        if ($scope.password !== $scope.repeatPassword) {
            // display error message
            DialogService.dialog(gettextCatalog.getString('Error'),
                gettextCatalog.getString('Passwords are not the same.')
            )
            return;
        }

        if (!$scope.passwordIsValid) {
            DialogService.dialog(gettextCatalog.getString('Error'),
                gettextCatalog.getString('Passwords does not sastify password requirements.')
            )
            return;
        }
        
        $scope.processing = true;
        
        sendPassword()
            .then(_ => window.location = './')
            .catch(data => {
                let txt = data;
                if (txt && txt.statusText)
                    txt = txt.statusText;
                    
                DialogService.dialog(gettextCatalog.getString('Error'),
                    gettextCatalog.getString('create password failed: ' + txt)
                )
                processing = false;
            });
    }

});