﻿(function () {
    'use strict';
    angular
        .module('eps.security')
        .controller('loginController', LoginController);

    LoginController.$inject = ['$state', 'authService', '$rootScope', '$location', 'profileService', 'localeService'];
    function LoginController($state, authService, $rootScope, $location, profileService, localeService) {
        var vm = this;

        vm.loginData = {
            userName: "",
            password: "",
            useRefreshTokens: false
        };

        vm.message = "";

        vm.login = login;

        function login() {
            authService.login(vm.loginData)
                .then(function () {
                    if (authService.deniedState) {
                        $state.go(authService.deniedState);
                    }
                    else {

                        //set locale before accessing the page
                        profileService.getCurrentUser().then(function (user) {
                            if (user)
                                localeService.setLocale(user.defaultLanguage);
                        });

                        if ($rootScope.redirectToUrl && $rootScope.redirectToUrl !== "/login") {
                            $location.url($rootScope.redirectToUrl);
                        }
                        else {
                            $state.go('admin');
                        }
                    }
                })
                .catch(function (err) {
                    if (err.data.error === 'invalid_grant') {
                        vm.message = 'Username e/o password non riconosciute.';
                    }
                    else if (err.data.error === 'password_expired') {
                        vm.message = 'Password scaduta.';
                        // todo: ridirigere a pagina per cambio password
                    }
                    else {
                        vm.message = "Errore sconosciuto. Contattare l'amministratore del sito.";
                    }
                });
        }
    }
})();