/**
 * BuildCompositeItemsCtrl Controller
 * Extracted from bookings module
 */

Bookings.controller('BuildCompositeItemsCtrl', ['$scope', 'build', '$uibModalInstance', 'Build', 'ErrorsHandler', function ($scope, build, $uibModalInstance, Build, ErrorsHandler) {

	$scope.build = angular.copy(build);

	// Add the selected stock item from the search bar to the corresponding list depending on the build status.
	$scope.addBuild = function (ev, data) {

		var build_items = $scope.build.status == 'planning' ? $scope.build.planned_components : $scope.build.stock.composite_items;

		// Check to see if the item exists
		var existingItem = _.findWhere(build_items, { id: data.id });
		if (existingItem) {
			existingItem.pivot.quantity++;
			return;
		}

		data.pivot = {
			quantity: 1
		};

		build_items.push(data);
	};

	$scope.save = function () {
		$scope.error = null;
		Build.update($scope.build, function (response) {
			$scope.loading = false;
			$uibModalInstance.close(response);
		}, function (response) {
			$scope.error = response.data.error.message;
		});
	};

	$scope.cancel = function () {
		$uibModalInstance.dismiss('cancel');
	};

	$scope.quantityOnOrder = function (build, item) {
		var quantity = 0;

		if (build.status == 'in_progress')
			_.each(build.ordered_components, function (c) {
				if (c.id == item.id) {
					quantity = c.pivot.quantity;
					return;
				}

			});

		return quantity;
	}

}]);
