/**
 * TaskTemplatesCtrl Controller
 * Extracted from bookings module
 */

Bookings.controller('TaskTemplatesCtrl', ['$scope', 'Tasks', 'ErrorsHandler', 'TaskTemplatesService', 'Messenger', function ($scope, Tasks, ErrorsHandler, TaskTemplatesService, Messenger) {

	/**
	 * Bind the task templates typeahead remote options to the scope.
	 *
	 * @object
	 */
	$scope.select2Options = TaskTemplatesService;


	/**
	 * Watch for when the completed items change and update the list
	 * accordingly.
	 */
	$scope.$watch('task.template_items', function (items) {
		$scope.parseItems(items);
	}, true);



	$scope.$on('task-updated', function () {
		var items = $scope.task.template_items;
		if (!items) return;
		$scope.parseItems(items)

	});



	$scope.parseItems = function (items) {
		// Loop through every template
		if ($scope.task) {
			_.each($scope.task.templates, function (template) {
				// Loop through every template item
				_.each(template.items, function (el) {

					el.done = _.find(items, function (item) { return item.id == el.id && item.pivot.value; }) ? true : false;
					el.notRequired = _.find(items, function (item) { return item.id == el.id && item.pivot.value == false; }) ? true : false;
				})

			});
		}
	};


	/**
	 * Watch the task templates and automatically save changes.
	 */
	// $scope.$watch('task.templates', function(items) {
	// 	if (typeof items != 'undefined' && $scope.task.id ) $scope.updateTask();
	// }, true);

	/**
	 * Update the task
	 */
	$scope.updateTask = function (ev) {
		Tasks.update($scope.task, function (response) {
			angular.extend($scope.task, response || {});
			Messenger("The task has been updated successfully");
		}, ErrorsHandler);
	};

	/**
	 * Marks the item as done or not done.
	 *
	 * @return null
	 */
	$scope.done = function (item) {
		item.notRequired = false;
		var params = angular.copy(item);
		params.item_id = item.id;
		params.id = $scope.task.id;

		Tasks.updateTemplateItem(params, function (response) {

		}, ErrorsHandler);
	};


	$scope.notRequired = function (item) {
		item.done = false;
		item.notRequired = true;
		var params = angular.copy(item);
		params.item_id = item.id;
		params.id = $scope.task.id;

		Tasks.updateTemplateItem(params, function (response) {

		}, ErrorsHandler);
	};

}])
