/**
 * RequestNonExistingPartCtrl Controller
 * Extracted from bookings module
 */

Bookings.controller('RequestNonExistingPartCtrl', ['$scope', 'Order', 'ErrorsHandler', 'PartsService', '$filter', '$ClientsManager', 'Stock', 'Part', '$uibModal', function ($scope, Order, ErrorsHandler, PartsService, $filter, $ClientsManager, Stock, Part, $uibModal) {
	$scope.initData = function () {
		$scope.data = {
			price_vat_included: 1,
			severity_id: 2,
			related_type: $scope.related_type,
			quantity: 1,
			type: 'non_stock',
			approval_required: 1
		};
		$scope.hideError = false; // Initialize error visibility flag
	};

	/**
	 * A link to parts array
	 *
	 * @type Array
	 */
	$scope.parts = PartsService.parts;

	/**
	 * Brings up the modal form.
	 *
	 * @return void
	 */
	$scope.showModal = function () {

		$scope.initData();
		$scope.modal = $uibModal.open({
			templateUrl: 'modals/request-non-existing-part-modal.html',
			scope: $scope
		});
	};

	/**
	 * 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 () {

		$scope.errors = null;
		$scope.loading = true;
		$scope.data.related_id = $scope.related.id;

		//If virtual mode enable, just create the stock and add the part to the parts array without creating it
		if ($scope.virtualMode) {
			//Check if exist a stock item with the given name
			Stock.get({ query: $scope.data.name }, function (response) {

				//If there is not stock with this name
				if (response.data.length == 0) {

					var price = ($scope.data.price_vat_included == 1) ? parseInt($scope.data.price_excluding_vat, 10) / (1 + parseInt($scope.vat, 10) / 100) : parseInt($scope.data.price_excluding_vat, 10);

					//The virtual mode creates
					var part = angular.extend({
						stock: $scope.data,
						price: price.toFixed(2),
						on_order: true
					}, $scope.data);

					$scope.hideModal();
					$scope.parts.push(part);

				} else {
					$scope.loading = false;
					$scope.hideError = false; // Reset the hide flag when new error occurs
					$scope.errors = "There is already a product with the same name.";
				}
			});
		}
		else {
			Part.requestPart($scope.data, function (response) {
				$scope.hideModal();
				$scope.parts.push(response);
			}, function (response) {
				$scope.loading = false;
				$scope.hideError = false; // Reset the hide flag when new error occurs
				$scope.errors = response.data.error.message;
			});
		}
	};

}])
