(function() {
	"use strict";

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

	controller.$inject = ['$scope', 'profileSvc'];
	function controller($scope, profileSvc) {
		var vm = this;
		vm.profile = $scope.profile;
		
		vm.saving = false;
		vm.success = false;
		vm.errorMessages = [];
		vm.save = save;

		function save() {
			vm.saving = true;
			vm.success = false;
			angular.copy([], vm.errorMessages);

			profileSvc.update(vm.profile)
				.success(function () {
					 vm.success = true;
					 vm.form.$setPristine();
				})
				.error(function (data) {
					vm.errorMessages = angular.copy(data.errorMessages, vm.errorMessages);
				})
				.finally(function () {
					vm.saving = false;
				});
		}
	}
})();