/**
 * CreateNonExitingBuildCtrl Controller
 * Extracted from bookings module
 */

Bookings.controller('CreateNonExitingBuildCtrl', ['$scope', 'Order', 'ErrorsHandler', 'PartsService', '$filter', '$ClientsManager', 'Stock', 'Build', '$uibModal', function ($scope, Order, ErrorsHandler, PartsService, $filter, $ClientsManager, Stock, Build, $uibModal) {

	$scope.initData = function () {
		$scope.build = {
			price: 0,
			quantity: 1,
			related_id: $scope.related.id,
			related_type: 'task',
			planned_components: []
		};
		$scope.hideError = false; // Initialize error visibility flag
	};

	$scope.product = {
		price_vat_included: 1,
		severity_id: 2,
		related_type: $scope.related_type,
		quantity: 1,
		type: 'non_stock',
		approval_required: 1
	};

	$scope.newStock = function () {

		var modalInstance = $uibModal.open({
			templateUrl: 'stock/stock-form.html',
			controller: 'StockModalCtrl',
			resolve: {
				categories: function () {
					return $scope.categories;
				},
				product_types: function () {
					return ["stock"];
				},
				item: function () {
					return {};
				},
				quick_mode: function () {
					return true;
				}
			}
		});

		modalInstance.result.then(function (response) {

			$scope.addComponent(null, response.data);
		}, function (response) {

		})['finally'](function () {
			// Show previous modal
		});
	};

	/**
	 * Brings up the modal form.
	 *
	 * @return void
	 */
	$scope.showModal = function () {
		$scope.initData();
		$scope.modal = $uibModal.open({
			templateUrl: 'modals/request-non-existing-build-modal.html',
			size: 'lg',
			scope: $scope
		});
	};


	$scope.addComponent = function (ev, item) {

		if (!$scope.build.planned_components) {
			$scope.build.planned_components = [];
		}
		else {

			// Check to see if the item already exists
			var existingItem = _.findWhere($scope.build.planned_components, { id: item.id });

			if (existingItem) {
				existingItem.pivot.quantity++;
				return;
			}
		}

		item.pivot = {
			quantity: 1
		};

		$scope.build.planned_components.push(item);
	};

	/**
	 * Hides the modal
	 *
	 * @return void
	 */
	$scope.hideModal = function () {
		$scope.modal.dismiss();
	};

	/**
	 * Form submission event, on success
	 * we clear up the form.
	 *
	 * @return void
	 */
	$scope.save = function () {

		if ($scope.build.planned_components.length == 0) {
			$scope.errors = "A build needs to have at least one item.";
			$scope.hideError = false; // Reset the hide flag when new error occurs
			return;
		}

		$scope.errors = null;
		$scope.loading = true;

		Build.save($scope.build, function (response) {
			$scope.hideModal();
			$scope.builds.push(response);
		}, function (response) {
			$scope.loading = false;
			$scope.hideError = false; // Reset the hide flag when new error occurs
			// Handle the specific error format from BuildsController
			if (response.data && response.data.error) {
				$scope.errors = response.data.error;
			} else if (response.data && response.data.error && response.data.error.message) {
				$scope.errors = response.data.error.message;
			} else {
				$scope.errors = "An error occurred while saving the build.";
			}
		});

	};

}])
