package com.atlassian.bitbucket.web.conditions;

import com.atlassian.bitbucket.project.Project;
import com.atlassian.bitbucket.permission.PermissionService;
import com.atlassian.bitbucket.user.ApplicationUser;

import java.util.Map;

/**
 * Verifies that the current user has a project permission
 *
 * <code>
 * <pre>
 * &lt;condition class="com.atlassian.bitbucket.web.conditions.HasProjectPermissionCondition">
 *     &lt;param name="permission">PROJECT_READ&lt;/param>
 * &lt;/condition>
 * </pre>
 * </code>
 */
public class HasProjectPermissionCondition extends AbstractPermissionCondition {

    public static final String PROJECT = "project";

    public HasProjectPermissionCondition(PermissionService permissionService) {
        super(permissionService, false);
    }

    @Override
    public boolean hasPermission(Map<String, Object> context) {
        Object project = context.get(PROJECT);

        return project instanceof Project &&
                permissionService.hasProjectPermission((Project) project, getPermission());
    }

    @Override
    public boolean hasPermission(Map<String, Object> context, ApplicationUser user) {
        Object project = context.get(PROJECT);

        return project instanceof Project &&
                permissionService.hasProjectPermission(user, (Project) project, getPermission());
    }

}
