/**
 * AddCustomerCtrl Controller
 * Extracted from clients module
 */

ClientsModule.controller('AddCustomerCtrl', ['$scope', '$uibModalInstance', 'Customer', 'ErrorsHandler', '$http', 'CustomerForm', 'Messenger', function ($scope, $uibModalInstance, Customer, ErrorsHandler, $http, CustomerForm, Messenger) {

	$scope.data = {};

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

	/**
	 * Saves the customer and closes the modal.
	 *
	 * @return null
	 */
	$scope.submit = function () {
		Customer.save($scope.data, function (response) {
			Messenger("I've successfully created the customer!");
			CustomerForm.onCreate(response.data);
			$uibModalInstance.close(response.data);
		}, ErrorsHandler);
	};

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

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

	/**
	 * Retrieves the full address 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';
		});
	};

}]);
