package com.atlassian.stash.internal.task;

import com.atlassian.bitbucket.repository.Repository;
import com.atlassian.bitbucket.auth.AuthenticationContext;
import com.atlassian.bitbucket.permission.Permission;
import com.atlassian.bitbucket.permission.PermissionService;
import com.atlassian.bitbucket.user.ApplicationUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @since 3.3
 */
@Component("taskPermissionsHelper")
public class TaskPermissionsHelper {

    private final AuthenticationContext authenticationContext;
    private final PermissionService permissionService;

    @Autowired
    public TaskPermissionsHelper(AuthenticationContext authenticationContext,
                                 PermissionService permissionService) {
        this.authenticationContext = authenticationContext;
        this.permissionService = permissionService;
    }

    /**
     * Checks whether the provided {@code user} can perform all operations on the {@code task}.
     *
     * @param context     the context of the task (e.g. a pull request)
     * @param task        the task
     * @return {@code true} if the <em>current authentication token</em> is the creator of the task or of the context
     */
    public boolean hasFullPermission(InternalTaskContext context, InternalTask task) {
        final ApplicationUser user = authenticationContext.getCurrentUser();
        return task.getAuthor().equals(user) || context.getCreatedBy().equals(user);
    }

    /**
     * @param repository the repository
     * @return true if current user is the repository admin
     */
    public boolean isRepoAdmin(Repository repository) {
        return permissionService.hasRepositoryPermission(repository, Permission.REPO_ADMIN);
    }

}