(function() {
    'use strict';

    angular
        .module('altaUsuarios')
        .controller('altaUsuariosController', Controller);

    Controller.$inject = ['$scope', 'apiFactory', '$mdToast', '$stateParams', '$timeout'];

    /* @ngInject */
    function Controller($scope, apiFactory, $mdToast, $stateParams, $timeout) {
        var vm = this;

        vm.token = $stateParams.token;
        vm.invalidToken = false;
        vm.loading = true;
        vm.buttonDisable = false;

        vm.save = save;

        init();

        vm.passRegex = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{8,16}$";
        vm.loading = true;

        function cleanDialog() {
          vm.loading = false;
          vm.userForm.$setPristine();
          vm.userForm.$setUntouched();
        }

        function save() {
          if ($scope.userForm.$valid) {
            vm.buttonDisable = true;
            vm.user.userName = vm.username;
            vm.user.password = vm.pass;

            apiFactory.updateUser(vm.user, vm.token.token)
              .then(function (res) {
                //console.log(res.data);
                $mdToast.show(
                  $mdToast.simple()
                    .textContent('Los datos se guardaron correctamente.')
                    .position("top right")
                    .hideDelay(4000)
                );

                // $timeout(function(){
                //   window.location = "http://yuli2.unc.edu.ar";
                // }, 4000);

              }, function (err) {
                vm.buttonDisable = false;
                console.log(err.data);
                $mdToast.show(
                  $mdToast.simple()
                    .textContent('Error al guardar los datos.')
                    .position("top right")
                    .hideDelay(4000)
                );
              });
          }
        }


        function init() {
          apiFactory.getTokenInfo(vm.token)
            .then(function (res) {
              vm.token = res.data;
              apiFactory.getUser(vm.token.user)
                .then(function (res) {
                  vm.user = res.data;
                  vm.loading = false;
                }, function (err) {
                  console.log(err);
                  vm.loading = false;
                });

              apiFactory.getPossibleNames(vm.token.user, vm.token)
                .then(function (res) {
                  vm.possibleNames = res.data;
                  vm.loading = false;
                }, function (err) {
                  console.log(err);
                  vm.loading = false;
                });

            }, function (err) {
              err.data ? console.log(err.data) : console.log(err);
              vm.invalidToken = true;
              vm.loading = false;
            });
        }

    }
})();
