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

import com.atlassian.fugue.Pair;
import com.atlassian.bitbucket.comment.Comment;
import com.atlassian.bitbucket.i18n.I18nKey;
import com.atlassian.bitbucket.mail.MailMessage;
import com.atlassian.bitbucket.notification.Notification;
import com.atlassian.stash.internal.notification.mention.MentionHelper;
import com.atlassian.bitbucket.user.ApplicationUser;

import java.util.Map;
import java.util.Set;
import java.util.function.Function;

public abstract class AbstractMentionNotificationHandler<T extends Notification> extends AbstractNotificationHandler<T> {

    protected final MentionHelper mentionHelper;
    protected final AbstractNotificationHandler<T> handler;

    public AbstractMentionNotificationHandler(NotificationHelper helper,
                                              MentionHelper mentionHelper,
                                              AbstractNotificationHandler<T> handler,
                                              String templateName) {
        super(helper, templateName);
        this.mentionHelper = mentionHelper;
        this.handler = handler;
    }

    @Override
    protected Map<String, Object> getContext(T notification) {
        Map<String, Object> context = handler.getContext(notification);
        context.put("mention", true);
        return context;
    }

    @Override
    public void handle(T notification, Iterable<ApplicationUser> recipients) {
        Pair<Iterable<ApplicationUser>, Set<ApplicationUser>> mentionedRecipients = mentionHelper.getFilteredRecipientsAndMentions(
                notification, getComment(notification), recipients);
        handler.handle(notification, mentionedRecipients.left());

        if (!mentionedRecipients.right().isEmpty()) {
            renderAndDispatch(notification, getContext(notification), mentionedRecipients.right());
        }
    }

    @Override
    protected I18nKey generateSubjectKey(T notification) {
        return handler.generateSubjectKey(notification);
    }

    @Override
    protected Function<MailMessage.Builder, MailMessage.Builder> getMessageTransformer(T notification) {
        return handler.getMessageTransformer(notification);
    }

    protected abstract Comment getComment(T notification);
}
