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

    module = angular.module(moduleName);

    module.service('task_edit_service', TaskEditService);

    function TaskEditService()
    {
        var service = this;

        service.$currentElement = null
        service.$modalElement = null

        service.startEdit = function(task, $taskElement)
        {
            if (service.$currentElement !== null)
            {
                service.$currentElement.trigger('cancelEdit');
                service.$currentElement = null;
            }

            service.$currentElement = $taskElement;
            service.$modalElement.trigger('taskEdit', task);
        };

        service.taskUpdated = function(task, callback)
        {
            var updateFunc = 'update';
            if (task.id === 0)
                updateFunc = 'add';

            task[updateFunc](function(data)
            {
                service.$modalElement.trigger('taskEditFinished', task);

                if (service.$currentElement !== null)
                {
                    service.$currentElement.trigger('editComplete', task);
                    service.$currentElement = null;
                }

                cla.showMessage(lmsg('projects.history.type.task_updated'), '', false);

                callback();
            }, function(data)
            {
                cla.showMessage(data.error, '', true);
            });

            return task;
        };

        service.taskDeleted = function(task)
        {
            if (service.$currentElement !== null)
            {
                service.$currentElement.trigger('taskDeleted', task);
                service.$currentElement = null;
            }
        };

        service.registerModal = function($modalElement)
        {
          service.$modalElement = $modalElement;
        };
    }
}());
