package com.atlassian.bitbucket.internal.key.ssh.condition;

import com.atlassian.bitbucket.internal.ssh.server.SshServer;
import com.atlassian.bitbucket.repository.Repository;
import com.atlassian.bitbucket.ssh.SshAccessKeyService;
import com.atlassian.bitbucket.ssh.SshConfigurationService;
import com.atlassian.plugin.PluginParseException;
import com.atlassian.plugin.web.Condition;

import java.util.Map;

public class ShowAccessKeySshCloneUrlCondition implements Condition {

    private static final String REPOSITORY = "repository";

    private final SshConfigurationService configurationService;
    private final SshAccessKeyService accessKeyService;
    private final SshServer sshServer;

    public ShowAccessKeySshCloneUrlCondition(SshAccessKeyService accessKeyService, SshServer sshServer,
                                             SshConfigurationService configurationService) {
        this.accessKeyService = accessKeyService;
        this.sshServer = sshServer;
        this.configurationService = configurationService;
    }

    @Override
    public void init(Map<String, String> params) throws PluginParseException {
    }

    @Override
    public boolean shouldDisplay(Map<String, Object> context) {
        if (sshServer.isRunning() && configurationService.getConfiguration().isAccessKeysEnabled()) {
            Object maybeRepository = context.get(REPOSITORY);
            if (maybeRepository instanceof Repository) {
                Repository repository = (Repository) maybeRepository;

                // Only repo admins or project admins will see key accesses so no additional perms checking needed
                return accessKeyService.existsForRepository(repository)
                        || accessKeyService.existsForProject(repository.getProject());
            }
        }

        // Don't show SSH clone URL if any of the following are true:
        // - The SSH server isn't running
        // - Access keys are not enabled
        // - The context "repository" isn't a repository
        // - No access keys exist for the context repository
        return false;
    }
}
