/**
 * EditCustomerCtrl Controller
 * Extracted from clients module
 */

ClientsModule.controller('EditCustomerCtrl', ['$scope', '$uibModalInstance', 'client', 'Customer', 'ErrorsHandler', '$http', function ($scope, $uibModalInstance, client, Customer, ErrorsHandler, $http) {

	$scope.data = client;

	$scope.service = {
		loading: false,
		isBusy: false
	};

	$scope.postcode = {
		icon: 'fa fa-crosshairs'
	};

	/**
	 * Saves the customer and closes the modal.
	 *
	 * @return null
	 */
	$scope.save = function () {
		$scope.service.loading = true;
		$scope.service.isBusy = true;
		
		Customer.update($scope.data, function (response) {
			$scope.service.loading = false;
			$scope.service.isBusy = false;
			$uibModalInstance.close(response.data);
		}, function(error) {
			$scope.service.loading = false;
			$scope.service.isBusy = false;
			ErrorsHandler(error);
		});
	};

	/**
	 * Closes the modal
	 *
	 * @return null
	 */
	$scope.close = function () {
		$uibModalInstance.dismiss('cancel');
	};

	/**
	 * Alias for close function
	 *
	 * @return null
	 */
	$scope.cancel = $scope.close;

	/**
	 * Retrieves the full adress for a given postcode
	 *
	 * @return null
	 */
	$scope.lookupPostcode = function (postcode) {
		$scope.postcode.icon = 'fa fa-spinner fa-spin';

		$http.post('/clients/postcode', { postcode: postcode }).success(function (res) {

			$scope.postcode.icon = 'fa fa-crosshairs';

			angular.extend($scope.data, {
				address2: res.postcode.street,
				town: res.postcode.town,
				county: res.postcode.county
			});

		}).error(function () {
			$scope.postcode.icon = 'fa fa-crosshairs';
		});
	};

}]);
