define([], function() {
    function TasksPermissionChecker(perms) {
        this.perms = {
            can_update_own_task_status: false,
            can_edit_own_task: false,
            can_edit_any_task: false,
            can_edit_project: false
        };
        for (var attrName in perms) { this.perms[attrName] = perms[attrName]; }
    }

    TasksPermissionChecker.prototype.perms = {};

    TasksPermissionChecker.prototype.HasTaskDragPerms = function(task, listId) {
        if (this.perms.can_edit_any_task)
            return true;

        // Task container and no other permission
        if (task === undefined && listId === undefined && !this.perms.can_edit_own_task && !this.perms.can_update_own_task_status)
            return false;

        // Task container and have either permission
        if ((task === undefined && listId === undefined) && (this.perms.can_edit_own_task || this.perms.can_update_own_task_status))
            return true;

        // Task check specifically
        return this.CanEditMyOwnTask(task) || this.CanUpdateMyTaskStatus(task, listId);
    };

    TasksPermissionChecker.prototype.HasListDragPerms = function() {
        return this.perms.can_edit_any_task;
    };

    TasksPermissionChecker.prototype.HasStatusDragPerms = function() {
        return this.perms.can_edit_project;
    };

    TasksPermissionChecker.prototype.IsMyTask = function(task) {
        if (parseInt(task.created_by.id) === this.perms.user_id)
            return true;

        for (var assigneeIndex = 0; assigneeIndex < task.assignees.length; assigneeIndex++)
        {
            if (parseInt(task.assignees[assigneeIndex].id) === this.perms.user_id)
                return true;
        }

        return false;
    }

    TasksPermissionChecker.prototype.CanEditMyOwnTask = function(task) {
        if (!this.perms.can_edit_own_task)
            return false;

        if (parseInt(task.created_by.id) === this.perms.user_id)
            return true;

        for (var assigneeIndex = 0; assigneeIndex < task.assignees.length; assigneeIndex++)
        {
            if (parseInt(task.assignees[assigneeIndex].id) === this.perms.user_id)
                return true;
        }

        return false;
    }

    TasksPermissionChecker.prototype.CanUpdateMyTaskStatus = function(task, listId) {
        if (this.CanEditMyOwnTask(task))
            return true;

        var myTaskInSameList = this.IsMyTask(task) && (listId === parseInt(task.section_id));
        return this.perms.can_update_own_task_status && myTaskInSameList;
    }

    return TasksPermissionChecker;
});
