package com.apobates.forum.thrones.event;

import com.github.davidmarquis.redisq.Message;
import com.github.davidmarquis.redisq.consumer.MessageListener;
import com.github.davidmarquis.redisq.consumer.retry.RetryableMessageException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.apobates.forum.core.entity.Posts;
import com.apobates.forum.core.entity.TopicConfig;
import com.apobates.forum.core.entity.proxy.TopicReplica;
import com.apobates.forum.core.impl.event.PostsPublishEvent;
import com.apobates.forum.core.service.TopicService;
import com.apobates.forum.letterbox.entity.ForumLetter;
import com.apobates.forum.letterbox.entity.ForumLetterReceiver;
import com.apobates.forum.letterbox.service.ForumLetterService;
import com.apobates.forum.utils.Commons;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Optional;

/**
 * 回复创建侦听器,如果话题开启了回复通知负责向楼主发送通知
 *
 * @author xiaofanku
 * @since 20190703
 */
@Component("postsReplyNotice")
public class PostsReplyNoticeListener implements MessageListener<PostsPublishEvent> {
    @Autowired
    private TopicService topicService;
    @Autowired
    private ForumLetterService forumLetterService;
    private final static Logger logger = LoggerFactory.getLogger(PostsReplyNoticeListener.class);
    
    @Override
    public void onMessage(Message<PostsPublishEvent> event) throws RetryableMessageException {
        logger.info("[Posts][PublishEvent][2]话题回复通知处理开始");
        Posts posts = event.getPayload().getPosts();
        Optional<TopicReplica> tc = topicService.getTopicConfig(posts.getTopicId());
        if(!tc.isPresent()){
            return;
        }
        TopicReplica topicReplica = tc.get();
        TopicConfig config = topicReplica.getConfigure();
        if (config.isNotify() && posts.getMemberId() != topicReplica.getMemberId()) { //自已不用通知自已
            String replyContent = Commons.htmlPurifier(posts.getContent());
            try {
                replyContent = replyContent.substring(0, 100) + "...";
            } catch (IndexOutOfBoundsException e) {}
            logger.info("[Posts][PublishEvent][2]回复通知正在保存");
            forumLetterService.create(
                    getReplyNotice(topicReplica, posts, Commons.optional(replyContent, "查看内容")), 
                    List.of(new ForumLetterReceiver(topicReplica.getMemberId(), topicReplica.getMemberNickname())));
        }
        logger.info("[Posts][PublishEvent][2]话题回复通知处理结束");
    }
    //生成回复通知
    private ForumLetter getReplyNotice(TopicReplica topic, Posts posts, String replyContent) {
        //title: 张三回复了您的主题
        //content: {张三}: {回复内容} #{主题}#
        String floorLink = String.format("/topic/%s.xhtml#posts-%d", topic.getConnect(), posts.getId());
        //(String title, String content, long author, String authorNames, ForumLetterTypeEnum type)
        return ForumLetter.noticeLetter(
                posts.getMemberNickname() + "回复了您的主题",
                String.format(
                        "<p><strong><a href=\"/member/%d.xhtml\">%s</a>: </strong>%s <a class=\"embed-link\" href=\"%s\">#%s#</a></p>", //<a href=\"/member/%d.xhtml\">%s</a>回复了您在<a href=\"/board/%d.xhtml\">%s</a>版块中发布的话题<a href=\"/topic/%d.xhtml\">#%s#</a>
                        posts.getMemberId(),
                        posts.getMemberNickname(),
                        replyContent,
                        floorLink,
                        topic.getTitle()));
    }
}