package com.apobates.forum.trident.event;

import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import com.apobates.forum.core.api.dao.TopicConfigDao;
import com.apobates.forum.core.api.dao.TopicDao;
import com.apobates.forum.core.entity.Posts;
import com.apobates.forum.core.entity.Topic;
import com.apobates.forum.core.entity.TopicConfig;
import com.apobates.forum.core.impl.event.PostsPublishEvent;
import com.apobates.forum.letterbox.api.service.ForumLetterService;
import com.apobates.forum.letterbox.entity.ForumLetter;
import com.apobates.forum.utils.Commons;
import org.springframework.stereotype.Component;

/**
 * 回复创建侦听器,如果话题开启了回复通知负责向楼主发送通知
 * 
 * @author xiaofanku
 * @since 20190703
 */
@Component
public class PostsReplyNoticeListener implements ApplicationListener<PostsPublishEvent>{
	@Autowired
	private TopicDao topicDao;
	@Autowired
	private TopicConfigDao topicConfigDao;
	@Autowired
	private ForumLetterService forumLetterService;
	private final static Logger logger = LoggerFactory.getLogger(PostsReplyNoticeListener.class);
	
	@Override
	public void onApplicationEvent(PostsPublishEvent event) {
		logger.info("[Posts][PublishEvent][2]话题回复通知处理开始");
		Posts posts = event.getPosts();
		Optional<TopicConfig> tc = topicConfigDao.findOneByTopic(posts.getTopicId());
		if(!tc.isPresent()){
			return;
		}
		
		Topic topic = topicDao.findOneForIndex(posts.getTopicId());
		if(tc.get().isNotify() && posts.getMemberId() != topic.getMemberId()){ //自已不用通知自已
			String replyContent=Commons.htmlPurifier(posts.getContent());
			try{
				replyContent = replyContent.substring(0, 100) + "...";
			}catch(IndexOutOfBoundsException e){}
			logger.info("[Posts][PublishEvent][2]回复通知正在保存");
			forumLetterService.create(getReplyNotice(topic, posts, Commons.optional(replyContent, "查看内容")));
		}
		logger.info("[Posts][PublishEvent][2]话题回复通知处理结束");
	}
	//生成回复通知
	private ForumLetter getReplyNotice(Topic 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 new ForumLetter(
				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()), 
				topic.getMemberId(), 
				topic.getMemberNickname());
	}
}
