package com.apobates.forum.letterbox.impl.event;

import com.apobates.forum.letterbox.dao.InboxDao;
import com.apobates.forum.letterbox.entity.ForumLetter;
import com.apobates.forum.letterbox.entity.ForumLetterReceiver;
import com.apobates.forum.letterbox.entity.Inbox;
import java.util.Set;
import java.util.stream.Collectors;
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 org.springframework.stereotype.Component;

/**
 * 将信件投递到信件人的收件箱中
 *
 * @author xiaofanku
 * @since 20200527
 */
@Component("letterdeliver")
public class ForumLetterPostInboxListener implements MessageListener<ForumLetterPostEvent> {
    @Autowired
    private InboxDao inboxDao;
    private final static Logger logger = LoggerFactory.getLogger(ForumLetterPostInboxListener.class);
    
    @Override
    public void onMessage(Message<ForumLetterPostEvent> event) throws RetryableMessageException {
        logger.info("[Letter][LetterPostEvent][1]信件投递通知开始");
        ForumLetterPostEvent lpe = event.getPayload();
        ForumLetter letter = lpe.getLetter();
        Set<ForumLetterReceiver> receivers = lpe.getReceivers();
        if (receivers.isEmpty()) {
            return;
        }
        Set<Inbox> letterEntryRecords = receivers.stream().map((ForumLetterReceiver fr)->new Inbox(fr.getMember(), letter.getAuthor(), letter.getNickname(), letter.getId())).collect(Collectors.toSet());
        inboxDao.batchSave(letterEntryRecords);
        logger.info("[Letter][LetterPostEvent][1]信件投递通知结束");
    }
}