package com.atlassian.stash.internal.pull.comment;

import com.atlassian.stash.internal.InternalConverter;
import com.atlassian.stash.internal.pull.PullRequestActivityDao;
import com.atlassian.bitbucket.pull.PullRequest;
import com.atlassian.bitbucket.pull.PullRequestPropertyContext;
import com.atlassian.bitbucket.pull.PullRequestPropertyProvider;
import com.google.common.base.Function;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Nonnull;
import java.util.Map;

@Component("commentCountProvider")
public class CommentCountProvider implements PullRequestPropertyProvider {

    private static final String COMMENT_COUNT = "commentCount";

    private final PullRequestActivityDao activityDao;

    @Autowired
    public CommentCountProvider(PullRequestActivityDao activityDao) {
        this.activityDao = activityDao;
    }

    @Override
    public void provideProperties(@Nonnull PullRequestPropertyContext context) {
        Map<Long, PullRequest> pullRequestsById = indexByGlobalId(context);
        // fetch the comment counts for each pull request and set as property
        Map<Long, Long> commentsByPullRequest = activityDao.countCommentsByPullRequest(pullRequestsById.keySet());
        for (Map.Entry<Long, Long> entry : commentsByPullRequest.entrySet()) {
            Long pullRequestId = entry.getKey();
            context.setProperty(pullRequestsById.get(pullRequestId), COMMENT_COUNT, entry.getValue());
        }
    }

    private Map<Long, PullRequest> indexByGlobalId(Iterable<PullRequest> context) {
        // index the pull requests per their global ID
        return Maps.uniqueIndex(context, new Function<PullRequest, Long>() {
            public Long apply(PullRequest pullRequest) {
                return InternalConverter.convertToInternalPullRequest(pullRequest).getGlobalId();
            }
        });
    }
}
