/*jshint -W100*/
/* this will remove accent warnings */

angular.module('ngBoilerplate.account', ['ui.router', 'ngResource', 'angular-md5'])
.config(function($stateProvider) {
    $stateProvider.state('login', {
        url:'/login',
        views: {
            'main': {
                templateUrl:'account/login.tpl.html',
                controller: 'LoginCtrl'
            },
            'footer': {
                templateUrl:'footer/footer.tpl.html',
                controller: 'LoginCtrl'
            }
        },
        data : { pageTitle : "Iniciar sesión" }
    })
    .state('register', {
            url:'/register',
            views: {
                'main': {
                    templateUrl:'account/register.tpl.html',
                    controller: 'RegisterCtrl'
                },
                'footer': {
                    templateUrl:'footer/footer.tpl.html',
                    controller: 'LoginCtrl'
                }
            },
            data : { pageTitle : "Crear cuenta" }
            }
    );
})
.factory('sessionService', function($http, md5, $state) {
    var session = {};
    session.login = function(data) {
        console.log("Login");
        //alert('user logged in with credentials ' + data.name + " and " + data.password);
        return $http.post("/basic-web-app/login", "username=" + data.name + "&password=" +md5.createHash(data.password || ''), {
            headers:{'Content-Type':'application/x-www-form-urlencoded'}
        }
        ).then(function(data){
            //alert('login successful');
            localStorage.setItem("name", data.headers().name);
            localStorage.setItem("type", data.headers().type);
            localStorage.setItem("session", data);
            $state.go("home");
        }, function(data){
            alert("Usuario y/o contraseña incorrectos");
        });
    };
    session.logout = function() {
        console.log("Logout");
        localStorage.removeItem("session");
        localStorage.removeItem("name");
        localStorage.removeItem("type");
    };
    session.isLoggedIn = function() {
        console.log("isLogedIn");
        if(localStorage.getItem("session") !== null && localStorage.getItem("name") !== null && localStorage.getItem("type") !== null){
            return true;
        }else{
            return false;
        }
    };
    session.isAdmin = function() {
        console.log("isAdmin");
        if(localStorage.getItem("session") !== null && localStorage.getItem("name") !== null){
            if (localStorage.getItem("type") == "3"){
                return true;
            }
        }
        return false;
    };
    session.isUser = function() {
        console.log("isUser");
        if(localStorage.getItem("session") !== null && localStorage.getItem("name") !== null){
            if (localStorage.getItem("type") == "0"){
                return true;
            }
        }
        return false;
    };
    session.isTempUser = function() {
        console.log("isTempUser");
        if(localStorage.getItem("session") !== null && localStorage.getItem("name") !== null){
            if (localStorage.getItem("type") == "1"){
                return true;
            }
        }
        return false;
    };
    return session;
})
.factory('accountService', function($resource, $http) {
    var service = {};
    service.register = function(account, success, failure) {
        console.log("register");
        var Account = $resource("/basic-web-app/rest/accounts");
        /*Prepare account for sending by setting the multiple coice variables*/
        account.gender = account.gender.name;
        account.province = account.province.name;
        account.specialty = account.specialty.name;
        Account.save({}, account, success, failure);
    };
    service.userExists = function(account, success, failure) {
        console.log("userExists");
        var Account = $resource("/basic-web-app/rest/accounts/activated");
        var data = Account.get({name:account.name}, function() {
            var accounts = data.accounts;
            if(accounts.length !== 0) {
                success(accounts[0]);
            } else {
                failure();
            }
        },
        failure);
    };
    service.getAllAccounts = function() {
        console.log("getAllAccounts");
        var Account = $resource("/basic-web-app/rest/accounts");
        return Account.get().$promise.then(function(data) {
            return data.accounts;
        });
    };
    service.getMyAccount = function() {
        console.log("getMyAccount");
        /*var Account = $resource("/basic-web-app/rest/accounts/name/"+localStorage.getItem("name"));
            return Account.get().$promise.then(function(data) {
              return data;
        });*/
        return $http.post("/basic-web-app/rest/accounts/name", "accountName=" + localStorage.getItem("name"), {
            headers:{'Content-Type':'application/x-www-form-urlencoded'}
        }
        ).then(function(data){
            return data.data;
        }, function(data){
            console.log("Error retrieveing user");
        });
    };
    return service;
})
.controller("LoginCtrl", function($scope, sessionService, accountService, $state) {
    $scope.login = function() {
        accountService.userExists($scope.account, function(account) {
            sessionService.login($scope.account);
        },
        function() {
            alert("Error logging in user");
        });
    };
})

.controller("RegisterCtrl", function($scope, $state, accountService) {
    /*$scope.register = function() {
                accountService.register($scope.account, 
        function(returnedData){ 
            alert("Le llegara un mensaje con su nuevo password"); 
            $state.go("home");
        },
        function(){
           alert("error registering user"); 
        });
    };*/
    
    $scope.save = function() {
    $scope.$broadcast('show-errors-check-validity');
    
    if ($scope.userForm.$valid && $scope.termsAndConditions){
        accountService.register($scope.account,
        function(returnedData){ 
            alert("Le llegara un mensaje con su nuevo password"); 
            $state.go("home");
        },
        function(){
            alert("Error registrando el nuevo usuario"); 
        });
    }
    if(!$scope.termsAndConditions){
        alert('Tiene que aceptar las condiciones de uso de esta aplicación si quiere crearse una cuenta');
    }
  };
  
  $scope.reset = function() {
    $scope.$broadcast('show-errors-reset');
    $scope.account = { name:'', number:'', specialty:'', age:'', gender:'', province:''};
    $scope.termsAndConditions = false;
  };
  
  $scope.provinces = [
    {'name': 'Albacete'},
    {'name': 'Alicante'},
    {'name': 'Almería'},
    {'name': 'Álava'},
    {'name': 'Asturias'},
    {'name': 'Ávila'},
    {'name': 'Badajoz'},
    {'name': 'Balears, Illes'},
    {'name': 'Barcelona'},
    {'name': 'Bizkaia'},
    {'name': 'Burgos'},
    {'name': 'Cáceres'},
    {'name': 'Cádiz'},
    {'name': 'Cantabria'},
    {'name': 'Castellón'},
    {'name': 'Ciudad Real'},
    {'name': 'Cordoba'},
    {'name': 'Coruña, A'},
    {'name': 'Cuenca'},
    {'name': 'Gipuzkoa'},
    {'name': 'Girona'},
    {'name': 'Granada'},
    {'name': 'Guadalajara'},
    {'name': 'Huelva'},
    {'name': 'Huesca'},
    {'name': 'Jaén'},
    {'name': 'León'},
    {'name': 'Lleida'},
    {'name': 'Lugo'},
    {'name': 'Madrid'},
    {'name': 'Málaga'},
    {'name': 'Múrcia'},
    {'name': 'Navarra'},
    {'name': 'Ourense'},
    {'name': 'Palencia'},
    {'name': 'Palmas, Las'},
    {'name': 'Pontevedra'},
    {'name': 'Rioja, La'},
    {'name': 'Salamanca'},
    {'name': 'Santa Cruz de Tenerife'},
    {'name': 'Segovia'},
    {'name': 'Sevilla'},
    {'name': 'Soria'},
    {'name': 'Tarragona'},
    {'name': 'Teruel'},
    {'name': 'Toledo'},
    {'name': 'Valencia'},
    {'name': 'Valladolid'},
    {'name': 'Zamora'},
    {'name': 'Zaragoza'},
    {'name': 'Ceuta'},
    {'name': 'Melilla'}];

$scope.genders = [
    {'name': 'Hombre'},
    {'name': 'Mujer'}];

$scope.specialties = [
    {'name': 'Farmacéutico'},
    {'name': 'Médico de atención primaria'},
    {'name': 'Médico especialista'}];
})

.directive('showErrors', function ($timeout, showErrorsConfig) {
      var getShowSuccess, linkFn;
      getShowSuccess = function (options) {
        var showSuccess;
        showSuccess = showErrorsConfig.showSuccess;
        if (options && options.showSuccess != null) {
          showSuccess = options.showSuccess;
        }
        return showSuccess;
      };
      linkFn = function (scope, el, attrs, formCtrl) {
        var blurred, inputEl, inputName, inputNgEl, options, showSuccess, toggleClasses;
        blurred = false;
        options = scope.$eval(attrs.showErrors);
        showSuccess = getShowSuccess(options);
        inputEl = el[0].querySelector('[name]');
        inputNgEl = angular.element(inputEl);
        inputName = inputNgEl.attr('name');
        if (!inputName) {
          throw 'show-errors element has no child input elements with a \'name\' attribute';
        }
        inputNgEl.bind('blur', function () {
          blurred = true;
          return toggleClasses(formCtrl[inputName].$invalid);
        });
        scope.$watch(function () {
          return formCtrl[inputName] && formCtrl[inputName].$invalid;
        }, function (invalid) {
          if (!blurred) {
            return;
          }
          return toggleClasses(invalid);
        });
        scope.$on('show-errors-check-validity', function () {
          return toggleClasses(formCtrl[inputName].$invalid);
        });
        scope.$on('show-errors-reset', function () {
          return $timeout(function () {
            el.removeClass('has-error');
            el.removeClass('has-success');
            return blurred = false;
          }, 0, false);
        });
        return toggleClasses = function (invalid) {
          el.toggleClass('has-error', invalid);
          if (showSuccess) {
            return el.toggleClass('has-success', !invalid);
          }
        };
      };
      return {
        restrict: 'A',
        require: '^form',
        compile: function (elem, attrs) {
          if (!elem.hasClass('form-group')) {
            throw 'show-errors element does not have the \'form-group\' class';
          }
          return linkFn;
        }
      };
    }
)
  
.provider('showErrorsConfig', function () {
    var _showSuccess;
    _showSuccess = false;
    this.showSuccess = function (showSuccess) {
      return _showSuccess = showSuccess;
    };
    this.$get = function () {
      return { showSuccess: _showSuccess };
    };
})

/*.controller('NewUserController', function($scope) {
  $scope.save = function() {
    $scope.$broadcast('show-errors-check-validity');
    
    if ($scope.userForm.$valid) {
      alert('User saved');
      $scope.reset();
    }
  };
  
  $scope.reset = function() {
    $scope.$broadcast('show-errors-reset');
    $scope.user = { name: '', email: '' };
  };
})*/;
