package com.atlassian.bitbucket.user;

import com.atlassian.bitbucket.permission.Permission;
import com.atlassian.bitbucket.util.Operation;
import com.google.common.collect.ImmutableSet;

import javax.annotation.Nonnull;
import java.util.Set;

/**
 * Escalated security context for testing purposes.
 */
public class DummyEscalatedSecurityContext implements EscalatedSecurityContext {

    private final ApplicationUser impersonating;
    private final Set<Permission> globalPermissions;

    public DummyEscalatedSecurityContext(ApplicationUser impersonating, Set<Permission> globalPermissions) {
        this.impersonating = impersonating;
        this.globalPermissions = globalPermissions;
    }

    @Override
    public <T, E extends Throwable> T call(@Nonnull Operation<T, E> operation) throws E {
        return operation.perform();
    }

    @Override
    public void applyToRequest() {

    }

    @Nonnull
    @Override
    public DummyEscalatedSecurityContext withPermission(@Nonnull Permission permission) {
        return withPermissions(ImmutableSet.of(permission));
    }

    @Nonnull
    @Override
    public DummyEscalatedSecurityContext withPermission(@Nonnull Object resource, @Nonnull Permission permission) {
        // Checking of resource-specific permissions not supported yet (feel free to add it if you need it).
        return this;
    }

    @Nonnull
    @Override
    public DummyEscalatedSecurityContext withPermissions(@Nonnull Set<Permission> permissions) {
        Set<Permission> newPermissions = ImmutableSet.<Permission>builder()
                .addAll(globalPermissions)
                .addAll(permissions)
                .build();
        return new DummyEscalatedSecurityContext(impersonating, newPermissions);
    }

    /**
     * @return the user that was impersonated with this context
     */
    public ApplicationUser getImpersonatingUser() {
        return impersonating;
    }

    /**
     * @return the global permissions that were added with this context
     */
    public Set<Permission> getGlobalPermissions() {
        return globalPermissions;
    }
}