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

import com.atlassian.bitbucket.repository.Repository;
import com.atlassian.bitbucket.ssh.SshAccessKeyService;
import com.atlassian.plugin.PluginParseException;
import com.atlassian.plugin.web.Condition;

import java.util.Map;

/**
 * Conditionally display web fragments based whether there is at least one SSH access key for a repository
 */
public class RepositoryHasSshAccessKeyCondition implements Condition {

    private final SshAccessKeyService accessKeyService;

    private boolean negate;

    public RepositoryHasSshAccessKeyCondition(SshAccessKeyService accessKeyService) {
        this.accessKeyService = accessKeyService;
    }

    @Override
    public void init(Map<String, String> params) throws PluginParseException {
        negate = Boolean.valueOf(params.get("negate"));
    }

    @Override
    public boolean shouldDisplay(Map<String, Object> context) {
        Repository repository = (Repository) context.get("repository");
        if (repository == null) {
            return false;
        }

        return negate != accessKeyService.existsForRepository(repository);
    }

}
