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

    const FORGET_PASSWORD_URL = './forget-password.cgi';
    const LOGIN_URL = './login.cgi';

    const sendForgetPasswordCode = () => {
        return authenticationApiConnector.post(FORGET_PASSWORD_URL, {'send-code': 1});
    }
    
    const sendPasswordForLogin = (data) => {
        const saltedpwd = CryptoJS.SHA256(CryptoJS.enc.Hex.parse(CryptoJS.enc.Utf8.parse($scope.password) + CryptoJS.enc.Base64.parse(data.Salt)));
        const noncedpwd = CryptoJS.SHA256(CryptoJS.enc.Hex.parse(CryptoJS.enc.Base64.parse(data.Nonce) + saltedpwd)).toString(CryptoJS.enc.Base64);
        
        return authenticationApiConnector.post(LOGIN_URL, {'password': noncedpwd})
    }

    const retrieveNonce = () => {
        return authenticationApiConnector.post(LOGIN_URL, {'get-nonce': 1});
    }

    $scope.login = () => {
        
        if ($scope.processing)
            return;

        $scope.processing = true;

        retrieveNonce()
            .then(data =>sendPasswordForLogin(data.data)
                            .then(_ => window.location = './')
                            .catch(data => {
                                let txt = data;
                                if (txt && txt.statusText)
                                    txt = txt.statusText;
                            
                                DialogService.dialog(gettextCatalog.getString('Error'),
                                    gettextCatalog.getString('Login failed: ' + txt)
                                )
                                $scope.processing = false;
                            })
            )
    }

    $scope.forgetPassword = function () {
        const bodyMessage = 'If you forget your password we can reset it. An email will be sent to the user email set in the settings. This code will be asked to recreate your password.';
        
        DialogService.dialog(
              gettextCatalog.getString('Forget password?')
            , gettextCatalog.getString(bodyMessage)
            , [ gettextCatalog.getString('Cancel'), gettextCatalog.getString('Send code') ]
            , function(ix) {
                if (ix == 1) {
                    $scope.processing = true

                    sendForgetPasswordCode()
                        .then(_ => window.location = './forget-password.html')
                        .catch(_ => {
                            DialogService.dialog(gettextCatalog.getString('Error'),
                                gettextCatalog.getString(_.statusText)
                            )
                            $scope.processing = false;
                        });
                }
            });
    }

});
