/* global angular, page_title, base_url, Noty, sha1 */

angular.module('app').controller("LoginCtrl", [
    '$scope',
    '$rootScope',
    '$state',
    '$window',
    'AuthService',
    function ($scope, $rootScope, $state, $window, AuthService) {
        $window.document.title = page_title + " :: Inicio de sesi\u00F3n";
        $scope.usuario_form = {username: '', password: '', captcha: ''};
        $scope.captcha_url = base_url + "index.php?/captcha/?r=" + Math.floor((Math.random() * 1000000) + 1);
        $scope.intentos_captcha = $rootScope.intentos_captcha;
        var app_last_state = JSON.parse(localStorage.getItem("app_last_state"));
        init();
        $scope.submit = function () {
            var data_send = {};
            data_send.username = $scope.usuario_form.username;
            data_send.password = sha1.hex($scope.usuario_form.password);
            data_send.intentos_captcha = $scope.intentos_captcha;
            data_send.captcha = $scope.usuario_form.captcha;
            AuthService.login(data_send).then(function (response) {
                $rootScope.intentos_captcha = 0;
                $rootScope.usuario_acceso = response.usuario;
                location.reload();
            }, function () {
                $scope.intentos_captcha += 1;
                $scope.usuario_form.captcha = "";
                $scope.cambia_captcha();
            });
        };
        $scope.cambia_captcha = function () {
            $scope.captcha_url = base_url + "index.php?/captcha/?r=" + Math.floor((Math.random() * 1000000) + 1);
        };
        function init() {
            AuthService.sessionActiva().then(function (data_response) {
                if (data_response.usuario_activo) {
                    if (app_last_state) {
                        if (app_last_state.params === null) {
                            if ($state.href(app_last_state.state) !== null) {
                                $state.go(app_last_state.state);
                            } else {
                                go_to_default();
                            }
                        } else {
                            delete(app_last_state.params["#"]);
                            if ($state.href(app_last_state.state) !== null) {
                                $state.go(app_last_state.state, app_last_state.params);
                            } else {
                                go_to_default();
                            }
                        }
                    } else {
                        go_to_default();
                    }
                } else {
                    $rootScope.usuario_acceso = false;
                }
            });
        }
        function go_to_default() {
            if ($state.href("main.bienvenido") !== null) {
                $state.go("main.bienvenido");
            } else {
                location.reload();
            }
        }
    }
]);
angular.module("app").controller('ConfirmarAccesoCtrl', [
    '$scope',
    '$rootScope',
    '$state',
    '$stateParams',
    '$window',
    '$timeout',
    'AuthService',
    function ($scope, $rootScope, $state, $stateParams, $window, $timeout, AuthService) {
        $window.document.title = page_title + " :: Confirmar acceso";
        $scope.show_form = false;
        $scope.form_pass = {
            password: '',
            confirmpassword: ''
        };
        $scope.show_pass = false;
        $scope.show_confirmpass = false;
        $timeout(function () {
            if (typeof $rootScope.usuario_acceso !== "undefined" && $rootScope.usuario_acceso) {
                logout();
            }
            var data_send = {codigo_encriptado: encodeURIComponent($stateParams.codigo)};
            AuthService.verificarCodigo(data_send).then(function () {
                $scope.show_form = true;
            });
        }, 100);
        $scope.submit = function () {
            var data_send = {
                password: sha1.hex(angular.copy($scope.form_pass.password)),
                confirmpassword: sha1.hex(angular.copy($scope.form_pass.confirmpassword))
            };
            data_send.codigo_encriptado = encodeURIComponent($stateParams.codigo);
            AuthService.confirmarAcceso(data_send).then(function (data_response) {
                $rootScope.usuario_acceso = data_response.usuario;
                $state.go("login");
            });
        };
        function logout() {
            AuthService.logout().then(function () {
                delete ($rootScope.usuario_acceso);
                $rootScope.intentos_captcha = 0;
            });
        }
    }
]);

angular.module("app").controller('EnviarUsuarioCtrl', [
    '$scope',
    '$window',
    '$state',
    'AuthService',
    function ($scope, $window, $state, AuthService) {
        $scope.show_form = true;
        $window.document.title = page_title + " :: Cambio de contrase\u00f1a";
        $scope.form_usuario = {
            username: ''
        };
        $scope.submit = function () {
            var data_send = angular.copy($scope.form_usuario);
            AuthService.validateAndSendCorreo(data_send).then(function () {
                $scope.show_form = false;
                new Noty({
                    theme: 'metroui',
                    type: 'alert',
                    text: 'Se envió un correo electrónico!!, revisa tu correo para poder cambiar tu contraseña.</div>',
                    layout: 'center',
                    timeout: false,
                    modal: true,
                    buttons: [
                        Noty.button('OK', 'btn btn-light', function ($noty) {
                            $noty.close();
                            $state.go('login');
                        })
                    ],
                    callbacks: {
                        afterClose: function () {
                            $scope.form_usuario = {
                                username: ''
                            };
                        }
                    }
                }).show();
            });
        };
    }
]);