package com.atlassian.stash.internal.comment.like.notification;

import com.atlassian.soy.renderer.SoyTemplateRenderer;
import com.atlassian.bitbucket.mail.HtmlCssInliner;
import com.atlassian.bitbucket.user.SecurityService;
import com.atlassian.bitbucket.user.ApplicationUser;
import com.atlassian.bitbucket.util.UncheckedOperation;
import com.google.common.collect.ImmutableMap;

import javax.annotation.Nonnull;

/**
 * Renders a comment like notification.
 *
 * @see CommentLikeData
 */
class CommentLikeNotificationRenderer {

    static final String EMAIL_CSS_MODULE_KEY = "com.atlassian.bitbucket.server.bitbucket-comment-likes:comment-likes-email-styles";
    static final String EMAIL_TEMPLATE_MODULE_KEY = "com.atlassian.bitbucket.server.bitbucket-comment-likes:comment-likes-email-templates";
    static final String TEMPLATE = "bitbucket.internal.commentLikes.email.like";

    private final HtmlCssInliner htmlCssInliner;
    private final SecurityService securityService;
    private final SoyTemplateRenderer soyTemplateRenderer;

    public CommentLikeNotificationRenderer(@Nonnull HtmlCssInliner htmlCssInliner,
                                           @Nonnull SecurityService securityService,
                                           @Nonnull SoyTemplateRenderer soyTemplateRenderer) {
        this.htmlCssInliner = htmlCssInliner;
        this.securityService = securityService;
        this.soyTemplateRenderer = soyTemplateRenderer;
    }

    @Nonnull
    public String render(@Nonnull final ApplicationUser recipient, @Nonnull final CommentLikeData likeData) {
        return securityService.impersonating(recipient, "Rendering like in user's locale").call(new UncheckedOperation<String>() {
            @Override
            public String perform() {
                return htmlCssInliner.inlineCss(soyTemplateRenderer.render(EMAIL_TEMPLATE_MODULE_KEY,
                        TEMPLATE, ImmutableMap.of(
                                "comment", likeData.getComment(),
                                "likers", likeData.getLikers(),
                                "recipient", recipient)),
                        EMAIL_CSS_MODULE_KEY);
            }
        });
    }

}
