(function()
{
    var template = require('../../html/directives/taskEdit.directive.html');

	var moduleName = 'claromentis.project';
	var module;

	try {
		module = angular.module(moduleName);
	} catch(err) {
		// named module does not exist, so create one
		module = angular.module(moduleName, []);
	}

	module
		.directive('projectTaskEdit', projectTaskEdit);

	projectTaskEdit.$inject = ['$timeout', 'task_edit_service', 'Task', 'confirmService'];
	function projectTaskEdit($timeout, service, Task, confirmService)
	{
		return {
			restrict: 'E',
			templateUrl: template,
			scope: {
    			taskDelete: '&',
				taskUpdate: '&'
			},
			controllerAs: 'edit',
			bindToController: true,
			controller: controller,
			link: link
		};

		function controller()
		{
			var ctrl = this;

			ctrl.task = new Task();
			ctrl.visible = false;

            this.$onInit = function() {
                ctrl.unique_id = ctrl.task.id;
            };

			// ctrl.userControl gives us an object shared with the user picker to allow us to run methods inside its scope (needed to reset Select2)
			ctrl.userControl = {};
			ctrl.htmlControl = {};

			ctrl.startTaskEdit = function()
			{
			    ctrl.visible = true;

			    // Need to let the modal content become visible in DOM before resetting it
			    $timeout(function() {
			        // Reset priority picker
				    ctrl.enableEditTaskPriority(ctrl.task);

                    // Reset the user picker if this is a new task.
                    if (ctrl.task.assignees === undefined)
                        ctrl.userControl.reset();

                    ctrl.htmlControl.onOpen();

                    ctrl.$modal.modal('show');
                }, 0);
			};

			ctrl.cancelTaskEdit = function(event)
			{
				ctrl.endTaskEdit(event);
			};

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

                ctrl.$modal.modal('hide');
                ctrl.visible = false;
            }

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

				var task = ctrl.task;

				task = service.taskUpdated(task, function(){
				    if (ctrl.taskUpdate !== undefined)
                        ctrl.taskUpdate({task: task})

                    ctrl.$modal.modal('hide');
                });
			};

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

                confirmService.show({
                    title: lmsg('projects.task.delete_task.title'),
                    message: lmsg('projects.task.delete_confirm'),
                }).then(function() {
                    ctrl.task.delete(function()
                    {
                        if (ctrl.taskDelete !== undefined)
                            ctrl.taskDelete({task: ctrl.task});

                        ctrl.$modal.modal('hide');
                        service.taskDeleted(ctrl.task);
                    }, function(data)
                    {
                        cla.showMessage(data.error, '', true);
                    });
                }, function() {});
			};

			ctrl.enableEditTaskPriority = function()
			{
				angular.element('.js-task-edit-priority').each(function()
				{
					if (angular.element(this).hasClass('select2-container'))
						return;

					// This should be automatic but it is invisible still at this point so not processed yet.
					angular.element(this).val(ctrl.task.priority);

					ctrl.colourSelect(angular.element(this));
				});
			};

			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
					width: "100%"
				});
			};
		}

		function link(scope, element, attrs, controller)
		{
		    controller.$modal = angular.element('#task-edit-modal');
		    service.registerModal(controller.$modal);

		    controller.$modal.on('taskEdit', function(event, task){
		        controller.task = angular.copy(task);

                $timeout(function() {
                    controller.startTaskEdit();
                }, 0);
            });

            controller.$modal.on('taskEditFinished', function(event){
                controller.endTaskEdit(event);
            });

		    // Handle the modal closing for any reason
            controller.$modal.on('hidden.bs.modal', function(){
                controller.htmlControl.onClose();

                controller.visible = false;
            });
		}
	}
}());
