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

import java.util.HashSet;
import java.util.Set;

import com.apobates.forum.letterbox.impl.event.ForumLetterPostEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import com.apobates.forum.letterbox.api.dao.InboxDao;
import com.apobates.forum.letterbox.entity.ForumLetter;
import com.apobates.forum.letterbox.entity.ForumLetterReceiver;
import com.apobates.forum.letterbox.entity.Inbox;

@Component
public class ForumLetterPostInboxListener implements ApplicationListener<ForumLetterPostEvent>{
	@Autowired
	private InboxDao inboxDao;
	private final static Logger logger = LoggerFactory.getLogger(ForumLetterPostInboxListener.class);
	
	@Override
	public void onApplicationEvent(ForumLetterPostEvent event) {
		ForumLetter letter = event.getLetter();
		logger.info("[Letter][LetterPostEvent][1]信件投递通知开始");
		if(letter.getReceivers().isEmpty()){
			return;
		}
		Set<Inbox> letterEntryRecords = new HashSet<>();
		for(ForumLetterReceiver fr : letter.getReceivers()){
			letterEntryRecords.add(new Inbox(fr.getMember(), letter.getAuthor(), letter.getNickname(), letter.getId()));
		}
		inboxDao.batchSave(letterEntryRecords);
		logger.info("[Letter][LetterPostEvent][1]信件投递通知结束");
	}
}
