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

import com.atlassian.bitbucket.commit.CommitRequest;
import com.atlassian.bitbucket.commit.CommitService;
import com.atlassian.bitbucket.commit.MinimalCommit;
import com.atlassian.bitbucket.NoSuchEntityException;
import com.atlassian.bitbucket.throttle.ResourceBusyException;
import com.atlassian.stash.internal.notification.handlers.NotificationHelper;
import com.atlassian.bitbucket.notification.pull.PullRequestMergedNotification;
import com.atlassian.bitbucket.repository.Repository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

public class PullRequestMergedNotificationHandler
        extends AbstractPullRequestNotificationHandler<PullRequestMergedNotification> {

    private static final Logger log = LoggerFactory.getLogger(PullRequestMergedNotificationHandler.class);

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

    private final CommitService commitService;

    public PullRequestMergedNotificationHandler(NotificationHelper helper, CommitService commitService) {
        super(helper, TEMPLATE);
        this.commitService = commitService;
    }

    @Override
    protected Map<String, Object> getContext(PullRequestMergedNotification notification) {
        Map<String, Object> context = super.getContext(notification);
        MinimalCommit commit = notification.getCommit();
        if (commit != null) {
            Repository repository = notification.getPullRequest().getToRef().getRepository();
            try {
                context.put("commit", commitService.getCommit(new CommitRequest.Builder(repository, commit.getId()).build()));
            } catch (NoSuchEntityException e) {
                // log a warning if the merge commit is missing
                String message = String.format(
                        "Merge of pull request %s in repository %s of project %s succeeded but failed to retrieve " +
                                "merge commit for hash %s",
                        notification.getPullRequest(), repository.getSlug(), repository.getProject().getKey(),
                        commit.getDisplayId());
                log.warn(message, e);
            } catch (ResourceBusyException e) {
                log.info("Couldn't retrieve the commit message for a pull request merge notification due to heavy server load.");
            }
        }
        return context;
    }

}
