/**
 * BookingsRmaCtrl Controller
 * Extracted from bookings module
 */

Bookings.controller('BookingsRmaCtrl', ['$scope', '$route', '$routeParams', '$location', '_rmaForm', '$ClientsManager', 'BookingsLocationManager', function ($scope, $route, $routeParams, $location, _rmaForm, $ClientsManager, BookingsLocationManager) {

	// ------------------------------------------------------------------------
	//
	//	SCOPE VARIABLES BELOW -->
	//
	// ------------------------------------------------------------------------

	$scope.data = _rmaForm.data;

	// working with the shared service managers
	$scope.clientManager = $ClientsManager;
	$scope.locationManager = BookingsLocationManager;

	$scope.form = _rmaForm;
	$scope.routeParams = $routeParams;

	// added by nadeem 13.2.17 - if the user use the add task to project button
	// then this will pass the project id forward to the back-end
	// the crated task will then be correctly associated with the correct project
	if (typeof ($scope.$parent.projectId != 'undefined')) {
		$scope.data.project_id = $scope.$parent.projectId;
	}

	// ------------------------------------------------------------------------
	//
	//	WATCHERS AND EVENT LISTENERS BELOW -->
	//
	// ------------------------------------------------------------------------
	$scope.$watch('data.site_user_id', function () {
		$scope.data.direct_dial = BookingsLocationManager.getUserDDI($scope.data.site_user_id);
	});

	$scope.$watch('data.site_id', function () {
		$scope.data.direct_dial = BookingsLocationManager.getUserDDI($scope.data.site_user_id);
	});


	// ------------------------------------------------------------------------
	//
	//	FUNCTIONS BELOW THIS LINE -->
	//
	// ------------------------------------------------------------------------

	$scope.save = _rmaForm.save;

	$scope.findItem = function (item) {
		return _.find($scope.data.items, function (el) {
			return el.id == item.id;
		});
	};

	$scope.addItem = function (item) {
		var existing_item = $scope.findItem(item);

		if (existing_item) {
			existing_item.quantity++;
		} else {
			$scope.data.items.push(item);
		}
	};

	$scope.removeItem = function (item) {
		$scope.data.items = _.reject($scope.data.items, function (el) {
			return el.id == item.id;
		});
	};

}]);
