/**
 * LinkTaskCtrl Controller
 * Extracted from bookings module
 */

Bookings.controller('LinkTaskCtrl', ['$scope', '$uibModalInstance', 'related_tasks', 'Tasks', 'currentTask', '$timeout', 'ErrorsHandler', function ($scope, $uibModalInstance, related_tasks, Tasks, currentTask, $timeout, ErrorsHandler) {

	var search_timeout;
	$scope.search = {
		query: ''
	};

	$scope.data = currentTask.related_tasks;

	$scope.$watch('search.query', function (value) {
		if (search_timeout) $timeout.cancel(search_timeout);

		search_timeout = $timeout(function () {
			$scope.load();
		}, 300);
	});

	$scope.load = function () {
		$scope.loading = true;

		Tasks.get({ search: $scope.search.query }, function (response) {
			$scope.tasks = _.reject(response.data, function (el) { return el.id == currentTask.id });
			$scope.loading = false;
		}, ErrorsHandler);

	};

	$scope.select = function (item) {
		if ($scope.exists(item)) return false;
		$scope.data.push(item);
	};

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

	$scope.exists = function (item) {
		var task = _.find($scope.data, function (el) {
			return el.id == item.id;
		});

		return (task) ? true : false;
	};

	$scope.link = function () {
		Tasks.update({ related_tasks: $scope.data, id: currentTask.id }, function (response) {
			$uibModalInstance.close(response);
		}, ErrorsHandler);
	};

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

}]);
