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

import com.atlassian.bitbucket.project.Project;
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 project. If no project
 * is available in the context but a repository is, its project is checked.
 */
public class ProjectHasSshAccessKeyCondition implements Condition {
    private final SshAccessKeyService accessKeyService;

    private boolean negate;

    public ProjectHasSshAccessKeyCondition(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) {
        Project project = (Project) context.get("project");

        if (project == null) {
            project = findProject(context, project);
        }

        if (project == null) {
            return false;
        }

        return negate != accessKeyService.existsForProject(project);
    }

    private Project findProject(Map<String, Object> context, Project project) {
        Repository repository = (Repository) context.get("repository");
        if (repository != null) {
            project = repository.getProject();
        }
        return project;
    }
}
