angular.module('builder.users', [])

.controller('UsersController', ['$scope', '$rootScope', '$state', 'user', function($scope, $rootScope, $state, user) {

	$scope.loading = false;

	$scope.loginInfo = {};

	if ($scope.isDemo) {
		$scope.loginInfo.email = 'demo@demo.com';
		$scope.loginInfo.password = 'demo';
	}

	$scope.registerInfo = {};

	$scope.errors = {};
	
	$scope.login = function() {
		$scope.loading = true;

		user.login($.extend({}, $scope.loginInfo)).error(function(data) {
			$scope.errors = data;
		}).success(function(user) {
			$('.login-container').addClass('animated fadeOutDown');
						
			setTimeout(function() {
				$rootScope.user = user;
				$state.go('dashboard');
			}, 550);
			
		}).finally(function(data) {
			$scope.loading = false;
		});
	};

	$scope.register = function() {
		$scope.loading = true;

		user.register($.extend({}, $scope.registerInfo)).error(function(errors) {
			$scope.errors = errors;
		}).success(function(user) {
			$('.login-container').addClass('animated fadeOutDown');
						
			setTimeout(function() {
				$rootScope.user = user;
				$state.go('dashboard');
			}, 550);

		}).finally(function(data) {
			$scope.loading = false;
		});
	};

}])

.factory('user', ['$http', '$cookieStore', '$rootScope', '$state', function($http, $cookieStore, $rootScope, $state) {
	
	var user = {

		login: function(credentials) {
			return $http.post('users/login', credentials);
		},

		register: function(credentials) {
			return $http.post('users/register', credentials);
		},

		logout: function() {
			return $http.post('users/logout').success(function(data) {
				$cookieStore.remove('blUser');
				$rootScope.user = false;

				$state.go('home');
			});
		},

	};

	return user;
}])

.directive('blFormValidator', ['elements', function(elements) {
    return {
   		restrict: 'A',
      	link: function($scope, el) {
      		var form = $('form');

      		$scope.$watch('errors', function(newErrors, oldErrors) {

      			//remove old errors
      			$('.form-error').remove();

      			$.each(newErrors, function(field, message) {

      				//if there's no field name append error as alert before the first input field
      				if (field == '*') {
					    $('#login-page .alert').show().addClass('animated shake').find('.message').text(message);
      				} else {
      					var field = $('[name="'+field+'"]');

      					$('<span class="form-error help-block">'+message+'</span>').appendTo('#login-page').css({
      						top: field.offset().top - 4,
      						left: field.offset().left + field.outerWidth(),
      					}).addClass('animated flipInX');
      				}
      			});
      		});
      	}
    };
}])