(function()
{
    var template = require('../../html/directives/taskAddButton.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('projectTaskAdd', projectTaskAdd);

	projectTaskAdd.$inject = ['$timeout', 'task_edit_service', 'Task'];
	function projectTaskAdd($timeout, service, Task)
	{
		return {
			restrict: 'E',
			templateUrl: template,
			scope: {
                sectionId: '=',
                projectId: '=',
                onTaskAdded: '&'
			},
			controllerAs: 'add',
			bindToController: true,
			controller: controller,
            link: link
		};

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

            ctrl.$onInit = function()
            {
                ctrl.id = 'js-task_add_button_' + ctrl.sectionId;
                ctrl.blankTask = new Task();
                ctrl.blankTask.project_id = parseInt(ctrl.projectId);
                ctrl.blankTask.section_id = parseInt(ctrl.sectionId);
            }

            ctrl.startTaskEdit = function(event, section_id)
            {
                ctrl.task = angular.copy(ctrl.blankTask);

                event.preventDefault();
                angular.element('.js-task_add_button_' + section_id).tooltip('hide');
                service.startEdit(ctrl.task, ctrl.$element);
            };

			ctrl.taskAdded = function(task)
            {
                ctrl.onTaskAdded({task: task});
            }
		}

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