package com.atlassian.stash.internal.pull.cleanup.conditions;

import com.atlassian.plugin.PluginParseException;
import com.atlassian.plugin.web.Condition;
import com.atlassian.bitbucket.pull.PullRequest;
import com.atlassian.bitbucket.repository.Repository;
import com.atlassian.bitbucket.scm.git.GitAgent;
import com.atlassian.bitbucket.scm.git.GitScm;

import java.util.Map;

/**
 * Check if the source repository of a pull request is a Git repository and
 * if the source branch still exists in that repository.
 */
public class HasGitSourceBranchCondition implements Condition {

    private final GitAgent gitAgent;

    public HasGitSourceBranchCondition(GitAgent gitAgent) {
        this.gitAgent = gitAgent;
    }

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

    @Override
    public boolean shouldDisplay(Map<String, Object> context) {
        PullRequest pullRequest = (PullRequest) context.get("pullRequest");
        Repository sourceRepository = pullRequest.getFromRef().getRepository();

        if (!GitScm.ID.equals(sourceRepository.getScmId())) {
            return false;
        }

        String sourceBranch = pullRequest.getFromRef().getId();
        return null != gitAgent.resolveBranch(sourceRepository, sourceBranch, true);
    }

}
