package com.atlassian.bitbucket.web.conditions;

import com.atlassian.bitbucket.auth.AuthenticationContext;
import com.atlassian.bitbucket.pull.PullRequest;
import com.atlassian.bitbucket.pull.PullRequestParticipant;
import com.atlassian.bitbucket.user.ApplicationUser;
import com.atlassian.plugin.PluginParseException;
import com.atlassian.plugin.web.Condition;
import com.google.common.collect.Sets;

import java.util.Map;
import java.util.Set;

/**
 * A condition which checks if the current user has approved the current pull request
 */
public class HasApprovedPullRequestCondition implements Condition {

    private static final String PULL_REQUEST = "pullRequest";
    private final AuthenticationContext authenticationContext;

    public HasApprovedPullRequestCondition(AuthenticationContext authenticationContext) {
        this.authenticationContext = authenticationContext;
    }

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

    @Override
    public boolean shouldDisplay(Map<String, Object> context) {
        PullRequest pullRequest = (PullRequest) context.get(PULL_REQUEST);

        Set<PullRequestParticipant> allParticipants = Sets.newLinkedHashSet();
        allParticipants.add(pullRequest.getAuthor());
        allParticipants.addAll(pullRequest.getReviewers());
        allParticipants.addAll(pullRequest.getParticipants());

        ApplicationUser currentUser = authenticationContext.getCurrentUser();
        if (currentUser != null) {
            String currentUsername = currentUser.getName();
            for (PullRequestParticipant participant : allParticipants) {
                if (currentUsername.equals(participant.getUser().getName())) {
                    return participant.isApproved();
                }
            }
        }

        return false;
    }
}
