/**
 * PartCompositeItemsCtrl Controller
 * Extracted from bookings module
 */

Bookings.controller('PartCompositeItemsCtrl', ['$scope', 'part', '$uibModalInstance', 'Part', 'ErrorsHandler', function ($scope, part, $uibModalInstance, Part, ErrorsHandler) {

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

	$scope.addPart = function (ev, data) {

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

		data.pivot = {
			quantity: 1
		};

		$scope.part.composite_items.push(data);
	};

	$scope.save = function () {
		Part.update($scope.part, function (response) {
			$scope.loading = false;
			$uibModalInstance.close(response);
		}, ErrorsHandler);
	};

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

}]);
