package com.atlassian.stash.internal.notification.pull.handlers;

import com.atlassian.bitbucket.notification.pull.PullRequestOpenedNotification;
import com.atlassian.bitbucket.pull.PullRequest;
import com.atlassian.bitbucket.pull.PullRequestParticipant;
import com.atlassian.bitbucket.user.ApplicationUser;
import com.atlassian.stash.internal.notification.handlers.NotificationHelper;
import com.atlassian.stash.internal.notification.mention.MentionHelper;
import com.atlassian.stash.internal.notification.usersettings.SendMode;
import com.google.common.collect.Sets;

import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

public class PullRequestOpenedNotificationHandler
        extends AbstractPullRequestNotificationHandler<PullRequestOpenedNotification> {

    private static final String TEMPLATE = "bitbucket.internal.notification.email.pullRequest.mentionDescription";

    private final MentionHelper mentionHelper;

    public PullRequestOpenedNotificationHandler(NotificationHelper helper, MentionHelper mentionHelper) {
        super(helper, TEMPLATE);
        this.mentionHelper = mentionHelper;
    }

    @Override
    public void handle(PullRequestOpenedNotification notification, Iterable<ApplicationUser> recipients) {
        PullRequest pullRequest = notification.getPullRequest();

        // Parse @mentioned users out of the pull request's description. If any of the reviewers was @mentioned,
        // they are filtered out to prevent them from receiving two e-mails
        Set<ApplicationUser> mentionedUsers = Sets.difference(
                mentionHelper.findUsers(notification, pullRequest.getDescription()),
                pullRequest.getReviewers().stream()
                        .map(PullRequestParticipant::getUser)
                        .collect(Collectors.toSet()));

        super.handle(notification, mentionedUsers);
    }

    @Override
    protected Set<SendMode> getEnabledSendModes() {
        // Opening a pull request is immediate also for users of batched, as it is the notification that "starts" a PR
        return SendMode.batchedAndImmediateSet();
    }
}
