var myTasksLoaded = myTasksLoaded || false;

(function()
{
	var moduleName = 'claromentis.my_tasks';
	var module;
    var template = require('../../html/components/task_item_dir.html');

	try {
		module = angular.module(moduleName);
	} catch(err) {
		// named module does not exist, so create one
		module = angular.module(moduleName, ['cla.core.lmsg', 'claromentis.project.tasks_util']);
	}

	projectListFilter = function(items, taskList) {
	    var projectIdSet = items.reduce(function (item, value) {
	        value[item.project_id] = true;
	        return value;
        }, {});

	    return items.filter(function(element, index, array) {
	        return element.project_id in projectIdSet;
        });
    }

	var projectFilter = function(items, projectId) {
		if (projectId === undefined) {
			return items;
		}

		return items.filter(function(element, index, array) {
			return element.project_id == projectId;
		});
	};

	var userFilter = function(items, userId) {
	    if (userId === undefined)
	        return items;

        return items.filter(function(element, index, array) {
            return element.assigned_to.id == userId;
        });
    }

    module.filter('projectListFilter', function() {
        return projectListFilter;
    });

	module.filter('projectFilter', function() {
		return projectFilter;
	});

    module.filter('userFilter', function() {
        return userFilter;
    });

	if (!myTasksLoaded)
	{
		module
			.directive('projectMyTasks', ["Task", projectMyTasks]);

		function projectMyTasks(Task) {
            return {
                restrict: 'E',
                templateUrl: template,
                scope: {
                    tasks: '=',
                    showCompleted: '=',
                    groupByProject: '=',
                    projectList: '=',
                    userId: '=',
                    showAssignees: '<',
                    showSectionNames: '<'
                },
                controllerAs: 'myTasks',
                bindToController: true,
                controller: controller
            };
        }

        controller.$inject = ["Task", "$scope"];

        function controller(Task, $scope)
        {
            var ctrl = this;
            ctrl.all_tasks = [];

            $scope.$watch('myTasks.tasks', function(newVals, oldVals) {
                ctrl.updateTasks();
            });

            ctrl.removeTask = function(task)
            {
                var tasks = [];
                angular.forEach(ctrl.all_tasks, function(t)
                {
                    if (t.id != task.id)
                        tasks.push(t);
                });
                ctrl.all_tasks = tasks;

                remainingTasks = projectFilter(tasks, task.project_id);
                if (!remainingTasks.length) {
                    ctrl.projectList = ctrl.projectList.filter(function (item) {
                        return item.id != task.project_id;
                    });
                }
            };

            ctrl.taskCompleteToggledCallback = function(task)
            {
                // zero-length timeout so we run after digest
                setTimeout(function() {
                    var master_task_index = 0;
                    for (var i = 0; i < ctrl.all_tasks.length; i++) {
                        if (ctrl.all_tasks[i].id == task.id)
                            master_task_index = i;
                    }

                    if (task.is_complete) {
                        task.setComplete(function () {
                            if (task.is_complete) {
                                if (!ctrl.showCompleted)
                                    ctrl.removeTask(task);
                                else
                                    cla.showMessage(lmsg("projects.component.task_completed"));
                            }
                        }, function (task, response) {
                            task.is_complete = false;
                            cla.showMessage(response.error, '', true);
                        });
                        ctrl.all_tasks[master_task_index] = task;
                    } else {
                        task.setIncomplete(function () {
                            // do not execute if task status has changed again
                            if (!task.is_complete) {
                                cla.showMessage(lmsg("projects.component.task_incomplete"));
                            }
                        }, function (task, response) {
                            task.is_complete = false;
                            cla.showMessage(response.error, '', true);
                        });
                        ctrl.all_tasks[master_task_index] = task;
                    }
                }, 0);
            };

            ctrl.updateTasks = function() {
                ctrl.all_tasks.length = 0;
                angular.forEach(ctrl.tasks, function(task)
                {
                    var new_task = new Task();
                    new_task.loadFromArray(task);
                    ctrl.all_tasks.push(new_task);
                });
            }
        }
    }

	myTasksLoaded = true;
}());
