var task_template = require('../../html/directives/task.directive.html');
var taskItemLoaded = taskItemLoaded || false;

(function()
{
	var moduleName = 'claromentis.project.tasks_util';
	var module = angular.module(moduleName);

	if (!taskItemLoaded)
	{
		module
			.directive('projectTaskItem', projectTaskItem);

        projectTaskItem.$inject = ['task_edit_service', 'userListService'];
		function projectTaskItem(taskEditService, userListService) {
			return {
				restrict: 'E',
				templateUrl: function(elem,attrs) {
					return attrs.templateUrl || task_template
				},
				scope: {
					task: '=',
                    showProjectName: '=',
                    showSectionName: '=',
                    currentUserId: '@',
					useDragAndDrop: '@',
                    display: '@',
					listPrefix: '@',
					taskUpdate: '&',
					taskDelete: '&',
					taskCompleteToggled: '&',
					titleLength: '@',
                    showAssignees: '<',
                    list: '<',
                    showSource: '@',
                    allowDrag: '<'
				},
				controllerAs: 'item',
				bindToController: true,
				controller: controller,
				link: link
			};

			function controller()
			{
				var ctrl = this;
                ctrl.showSource = !!ctrl.showSource;
				ctrl.$element = null;

                this.$onInit = function() {
                    ctrl.updateTitle();

                    // Set default if needed
                    if ((ctrl.showAssignees !== 'others') &&
                        (ctrl.showAssignees !== 'none'))
                    {
                        ctrl.showAssignees = 'all';
                    }

                    if (ctrl.currentUserId === undefined)
                        ctrl.currentUserId = 0;
                    else
                        ctrl.currentUserId = parseInt(ctrl.currentUserId);

                    // Default to allowing dragging if unspecified
                    if (ctrl.allowDrag === undefined)
                        ctrl.allowDrag = true;
                };

				ctrl.startTaskEdit = function(event, id)
				{
					event.preventDefault();
					angular.element('.js-task_edit_button_' + id).tooltip('hide');
					taskEditService.startEdit(ctrl.task, ctrl.$element);
				};

				ctrl.completeToggled = function()
				{
					ctrl.taskCompleteToggled({task: ctrl.task});
				};

				ctrl.taskUpdated = function(task)
				{
                    ctrl.taskUpdate({task: ctrl.task});

                    ctrl.task.id = task.id;
                    ctrl.task.title = task.title;
                    ctrl.task.description = task.description;
                    ctrl.task.project_id = task.project_id;
                    ctrl.task.assignees = task.assignees;
                    ctrl.task.due_date = task.due_date;
                    ctrl.task.priority = parseInt(task.priority);
                    ctrl.task.is_private = task.is_private;
                    ctrl.task.duration = task.duration;
                    ctrl.task.duration_units = task.duration_units;
                    ctrl.task.due_date_type = task.due_date_type;
                    ctrl.task.due_date_formatted = task.due_date_formatted;
                    ctrl.task.perms = task.perms;

					ctrl.updateTitle();
				};

				ctrl.updateTitle = function()
				{
					// Truncate the title if needed and requested
					var max_length = parseInt(ctrl.titleLength);
					if (typeof ctrl.titleLength === 'undefined')
						max_length = 0;
					ctrl.task.title_truncated = ctrl.task.title;
					if ((max_length !== 0) &&
						(ctrl.task.title.length > max_length))
					{
						ctrl.task.title_truncated = ctrl.task.title_truncated.substring(max_length, 0) + '…';
					}
				};

				ctrl.taskDeleted = function(task)
                {
                    if (ctrl.taskDelete !== undefined)
                        ctrl.taskDelete(task);
                };

                ctrl.getAssignees = function()
                {
                    if (ctrl.showAssignees === 'none')
                        return [];
                    if (ctrl.showAssignees === 'all')
                        return ctrl.task.assignees;

                    // Must be 'others' so strip out current user
                    var userId = parseInt(ctrl.currentUserId);
                    var assignees = [];
                    for (var assigneeIndex = 0; assigneeIndex < ctrl.task.assignees.length; assigneeIndex++)
                    {
                        if(ctrl.task.assignees[assigneeIndex].id !== userId)
                            assignees.push(ctrl.task.assignees[assigneeIndex]);
                    }

                    return assignees;
                };

				ctrl.noDrag = function()
                {
                    return ctrl.allowDrag === false ? true : undefined;
                };

                ctrl.additionalAssigneesClick = function() {
                    userListService.showUsersList(ctrl.task.assignees);
                };
			}

			function link(scope, element, attrs, controller)
			{
			    controller.$element = element;
			    controller.$element.on('cancelEdit', function(event){
                });
                controller.$element.on('editComplete', function(event, task){
                    controller.taskUpdated(task);
                });
                controller.$element.on('taskDeleted', function(event, task){
                    controller.taskDeleted(task);
                });

				// Default to showing all parts unless told otherwise
				controller.showEdit = (attrs.showEdit !== 'false');
				controller.showPrivate = (attrs.showPrivate !== 'false');
				controller.showDate = (attrs.showDate !== 'false');
				controller.showFiles = (attrs.showFiles !== 'false');
				controller.showComments = (attrs.showComments !== 'false');
			}
		}
	}

	taskItemLoaded = true;
}());
