(function() {
	"use strict";

	window.app.directive('userEdit', function (){
		return {
			scope: {
				user: "="
			},
			templateUrl: '/user/template/userEdit.tmpl.cshtml',
			controller: controller,
			controllerAs: 'vm'
		}
	});

	controller.$inject = ['$scope', 'userSvc'];
	function controller($scope, userSvc) {
		var vm = this;
		vm.user = angular.copy($scope.user);
		vm.save = save;

		vm.saving = false;
		vm.userSvc = userSvc;

		vm.statusMessage = "Edit this user";
		vm.errorMessages = [];

		function save() {
			vm.statusMessage = null;
			vm.saving = true;
			userSvc.edit($scope.user, vm.user)
				.success(function () {
					//Close the modal
					$scope.$parent.$close();
				})
				.error(function(data) {
					vm.errorMessages = angular.copy(data.errorMessages, vm.errorMessages);
				})
				.finally(function() {
					vm.saving = false;
				});
		}
	}
})();