(function()
{
	var moduleName = 'projectDetailApp';

	angular.module(moduleName)
		.controller("projectTasksCtrl", ['$scope', '$http', 'Task', 'TaskSection', 'growl.service', 'tasksService', 'projectPreloadFactory', projectTasksController])
        .filter('filterSections', function() {
            return function(sections, showEmpty) {
                if (showEmpty)
                    return sections;

                var out = [];

                for (var i = 0; i < sections.length; i++) {
                    if (sections[i].tasks.length)
                        out.push(sections[i]);
                }

                return out;
            };
        })

	function projectTasksController($scope, $http, Task, TaskSection, growlService, tasksService, preload)
	{
		var ctrl = this;

		/**
		 * Data setup
		 */

		ctrl.show_completed = false;
		ctrl.project_id = preload.id;
		ctrl.duration_units = preload.duration_units;

		ctrl.perms = preload.perms;
		ctrl.can_see_empty_sections = ctrl.perms.can_add_task || ctrl.perms.can_edit_any_task;

        ctrl.tasks = tasksService.tasks;
        ctrl.lists = tasksService.lists;
        ctrl.statuses = tasksService.statuses;
        ctrl.archiveDate = preload.archive_date;

		/**
		 * Task methods
		 */

		ctrl.toggleAddTask = function(section)
		{
			if (!section.new_task.is_edit)
			{
				ctrl.resetNewTask(section);
				ctrl.enableNewTaskPriority(section);
				section.new_task.is_edit = true;
			} else
			{
				section.new_task.is_edit = false;
			}
		};

		ctrl.resetNewTask = function(section)
		{
			section.new_task = new Task();
			section.new_task.section_id = section.id;
			section.new_task.project_id = ctrl.project_id;
			section.new_task.assigned_to_id = null;
			section.new_task.due_date = '';
			section.new_task.assigned_to = {name: '', id: null};
			section.new_task.priority = '0';
			section.new_task.duration_units = ctrl.duration_units;
			if (typeof section.new_task.control.reset !== 'undefined')
			{
				section.new_task.control.reset();
			}
		};

		ctrl.cancelAddTask = function(event, section)
		{
			section.new_task.show = false;
			ctrl.resetNewTask(event, section);

			$('#collapseAddTask-' + section.id).collapse('toggle');
		};

		/**
		 * Section methods
		 */

		ctrl.resetNewSection = function()
		{
			ctrl.new_section = new TaskSection();
			ctrl.new_section.project_id = ctrl.project_id;
		};

		ctrl.showAddSection = function() {
			ctrl.add_section = true;
			setTimeout(function()
			{
				angular.element('#new_section_colour-inner').css('background-color', ctrl.new_section.colour);
			},0);
		};

		ctrl.addSection = function(event)
		{
			event.preventDefault();

			ctrl.new_section.add(function()
			{
				var new_section = angular.extend(new TaskSection(), ctrl.new_section);
				new_section.setDisplayOrder(ctrl.lists.length + 1);
				ctrl.lists.push(new_section);
				ctrl.resetNewTask(new_section);

				ctrl.resetNewSection();
				ctrl.add_section = false;

				angular.element('#add-list').modal('hide');
				growlService.showSuccess(lmsg('projects.project.task_list.created'));
            }, function(data)
			{
			    growlService.showError(data.error);
			});
		};

		ctrl.cancelAddSection = function (event)
		{
			event.preventDefault();
			ctrl.resetNewSection();
			ctrl.add_section = false;
		};

		ctrl.deleteSection = function(event, section)
		{
			event.preventDefault();

			if(confirm(lmsg('projects.js.are_you_sure')))
			{
				angular.element('#delete-section-' + section.id).tooltip('hide');
				section.delete(function(section_id)
				{
					var section_list = [];
					for (var i = 0; i < ctrl.lists.length; i++)
					{
						if (ctrl.lists[i].id != section_id)
							section_list.push(ctrl.lists[i]);
					}
					ctrl.lists = section_list;
					$(this).tooltip('destroy');
				}, function(data)
				{
				    growlService.showError(data.error);
				});
			}
		};

		ctrl.saveSectionEdit = function(event, section)
		{
			event.preventDefault();

			section.update(function()
			{
				section.is_edit = false;
			}, function(data)
			{
			    growlService.showError(data.error);
			});

		};

		ctrl.startSectionEdit = function(event, section)
		{
			event.preventDefault();

			section.makeEditCopy();
			section.is_edit = true;
			setTimeout(function()
			{
				angular.element('#section_colour-' + section.id + '-inner').css('background-color', section.colour);
			},0);
		};

		ctrl.cancelSectionEdit = function(event, section)
		{
			event.preventDefault();

			section.is_edit = false;
		};

		ctrl.resetNewSection();



		ctrl.colourSelect = function(target)
		{
			target.select2({
				templateResult: function (data)
				{
					if (!data.id) { return data.text; }
					return '<span class="task-priority-option task-priority-' + data.id + '" style="display:inline-block; margin-right:0;">&nbsp</span> ' + data.text;
				},
				templateSelection: function formatPrioritySelection (data)
				{
					if (!data.id) { return data.text; }
					return '<span class="task-priority-option task-priority-' + data.id + '" style="display:inline-block; margin-right:0;">&nbsp</span> ' + data.text;
				},
				escapeMarkup: function(markup)
				{
					return markup;
				},
				minimumResultsForSearch: Infinity // Hide search box
			});
		};

		ctrl.enableNewTaskPriority = function(section)
		{
			var select = $('#section-task-edit-section-' + section.id + ' .js-task-priorities');
			if (select.hasClass('select2-container'))
				return;

			// This should be automatic but it is invisible still at this point so not processed yet.
			select.val(section.new_task.priority);

			ctrl.colourSelect(select);
		};

		ctrl.updateHistoryLog = function()
		{
			$scope.$root.$broadcast('updateHistoryLog', null);
		};

		ctrl.updateProjectProgress = function(progress)
		{
			$scope.$root.$broadcast('updateProjectProgress', progress);
		};
	}
}());
