/**
 * SubscribersCtrl Controller
 * Extracted from bookings module
 */

Bookings.controller('SubscribersCtrl', ['$scope', '$uibModalInstance', 'task', 'users', 'Tasks', 'ErrorsHandler', function ($scope, $uibModalInstance, task, users, Tasks, ErrorsHandler) {

	_.each(users, function (u) {
		var subscriber = _.find(task.subscribers, function (el) { return el.id == u.id; });
		if (subscriber) u.subscribed = true;
	});

	$scope.subscribers = task.subscribers;
	$scope.users = users;

	$scope.subscribe = function (user) {
		user.saving = true;
		task.subscribers.push(user);

		Tasks.update({ id: task.id, subscribers: task.subscribers }, function (response) {
			user.saving = false;
			user.subscribed = true;
		}, ErrorsHandler);
	};

	$scope.unsubscribe = function (user) {
		user.saving = true;
		task.subscribers = _.reject(task.subscribers, function (el) { return el.id == user.id; });
		$scope.subscribers = task.subscribers;

		Tasks.update({ id: task.id, subscribers: task.subscribers }, function (response) {
			user.saving = false;
			user.subscribed = false;
		}, ErrorsHandler);
	};

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

}]);
