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.service.PostsService;
import com.apobates.forum.core.entity.Posts;
import com.apobates.forum.core.entity.PostsMoodRecords;
import com.apobates.forum.core.impl.event.PostsMoodEvent;
import com.apobates.forum.letterbox.api.service.ForumLetterService;
import com.apobates.forum.letterbox.entity.ForumLetter;
import com.apobates.forum.utils.DateTimeUtils;
import org.springframework.stereotype.Component;

/**
 * 回复喜好动作通知
 * 
 * @author xiaofanku
 * @since 20191116
 */
@Component
public class PostsMoodNoticeListener implements ApplicationListener<PostsMoodEvent>{
	@Autowired
	private PostsService postsService;
	@Autowired
	private ForumLetterService forumLetterService;
	private final static Logger logger = LoggerFactory.getLogger(PostsMoodNoticeListener.class);
	
	@Override
	public void onApplicationEvent(PostsMoodEvent event) {
		PostsMoodRecords pmr = event.getRecords();
		if(!pmr.isLiked()){
			return; //讨厌的都不通知了
		}
		Optional<Posts> posts = postsService.get(pmr.getPostsId());
		if(!posts.isPresent()){
			return; //回复不存在
		}
		logger.info("[Posts][MoodEvent][1]回复喜好通知处理开始");
		Posts p = posts.get();
		String floorLink=String.format("/topic/%s.xhtml#posts-%d", p.getLazyTopic().getConnect(), p.getId());
		String content = String.format("<p>%s在%s为您的回复点赞, <a class=\"embed-link\" href=\"%s\">查看回复</a></p>", pmr.getMemberNickname(), DateTimeUtils.getRFC3339(pmr.getEntryDateTime()), floorLink);
		//ForumLetter(String title, String content, long receiver, String receiverNames)
		forumLetterService.create(new ForumLetter("您的回复收到一条点赞记录", content, p.getMemberId(), p.getMemberNickname()));
		logger.info("[Posts][MoodEvent][1]回复喜好通知处理结束");
	}
}
