angular.module('AddressBook',[])
.service("contactService",function($http,$q, validationService){
	var contactUrl = 'http://localhost:3000/contacts';
	var contacts = [];	
	
	function getContacts(){
		var deferral = $q.defer();
		
		$http.get(contactUrl)
		.then(function(res){
			while(res.data[0]){
				contacts.push(res.data.pop());
			};
			deferral.resolve(contacts);
		})
		
		return deferral.promise;
	};
	
	function addContact(contact){
		var i = contacts.push(contact);
		var request = $http.post(contactUrl+'/new',contact);
		request.then(function success(res){
				
		},
		function fail(){
			contacts.splice(i-1,1);
			alert("Sorry, we couldn't add your contact.");
		});
		return request;
	}
	
	return {
		getContacts:getContacts,
		addContact:addContact
	}
})

.service("validationService",Validation)

.controller("ContactList",function($scope,contactService){
	contactService.getContacts().then(function(contacts){
		$scope.contacts = contacts;
	})
})

.controller("AddContact",function($scope,contactService,validationService){
	$scope.contact = {
		name:"Ali",
		email:"Ali@baba.com"
	}
	$scope.addContact = function(){
		if (!validationService.isValidContact($scope.contact)){
			$scope.errorMessage = true;
			return false;
		};
		
		contactService.addContact(angular.copy($scope.contact));		
		$scope.contact = {};
	}
})
@@ -274,32 +274,8 @@
 s)%7B%0A
-%09%09%09while(res.data%5B0%5D)%7B%0A%09
 %09%09%09c
@@ -285,22 +285,19 @@
 acts
-.push(
+ = 
 res.data
 .pop
@@ -296,21 +296,8 @@
 data
-.pop());%0A%09%09%09%7D
 ;%0A%09%09
@@ -584,58 +584,8 @@
 1);%0A
-%09%09%09alert(%22Sorry, we couldn't add your contact.%22);%0A
 %09%09%7D)
@@ -975,19 +975,21 @@
 %09%09name:%22
-Ali
+Bronn
 %22,%0A%09%09ema
@@ -996,21 +996,63 @@
 il:%22
-Ali@baba.com%22
+bronn@anonymo.us%22,%0A%09%09occupation:%22Sellsword%22,%0A%09%09age:39%09%09
 %0A%09%7D%0A
@@ -1259,12 +1259,30 @@
 ct))
-;%09%09%0A
+%0A%09%09.then(function()%7B%0A%09
 %09%09$s
@@ -1300,13 +1300,84 @@
 t = %7B%7D;%0A
+%09%09%7D,function()%7B%0A%09%09%09alert(%22Sorry, we couldn't add your contact.%22);%0A%09%09%7D)%0A
 %09%7D%0A%7D)

update contact list logic to prevent bug.