package com.atlassian.bitbucket.internal.mirroring.upstream.user;

import com.atlassian.bitbucket.internal.mirroring.upstream.DefaultAddonUserHelper;
import com.atlassian.bitbucket.permission.EffectivePermission;
import com.atlassian.bitbucket.permission.EffectivePermissionsProvider;
import com.atlassian.bitbucket.permission.Permission;
import com.atlassian.bitbucket.permission.SimpleEffectiveGlobalPermission;
import com.atlassian.bitbucket.user.AbstractApplicationUserVisitor;
import com.atlassian.bitbucket.user.ApplicationUser;
import com.atlassian.bitbucket.user.ServiceUser;
import com.google.common.collect.ImmutableList;

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

/**
 * Elevates all mirror service users on the upstream to have PROJECT_READ privileges.
 */
public class MirroringAddonUserPermissionSupplier implements EffectivePermissionsProvider {

    private static Iterable<EffectivePermission> READ_ALL_PROJECTS =
            ImmutableList.<EffectivePermission>of(new SimpleEffectiveGlobalPermission(Permission.PROJECT_READ));

    @Nonnull
    @Override
    public Iterable<EffectivePermission> getPermissions(@Nonnull ApplicationUser user) {
        return user.accept(new AbstractApplicationUserVisitor<Iterable<EffectivePermission>>() {
            @Override
            public Iterable<EffectivePermission> visit(@Nonnull ServiceUser user) {
                if (DefaultAddonUserHelper.isAddonUser(user)) {
                    return READ_ALL_PROJECTS;
                }
                return defaultValue(user);
            }

            @Override
            protected Iterable<EffectivePermission> defaultValue(ApplicationUser user) {
                return Collections.emptySet();
            }
        });
    }
}

