package com.apobates.forum.thrones.event;

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.member.entity.ForumCalendarUnitEnum;
import com.apobates.forum.member.entity.MemberVipExchangeRecords;
import com.apobates.forum.member.impl.event.MemberVipExchangeEvent;
import com.apobates.forum.utils.DateTimeUtils;
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;
import java.time.LocalDateTime;
import java.util.List;

@Component("vipExchangeNotice")
public class MemberVipExchangeNoticeListener implements MessageListener<MemberVipExchangeEvent> {
    @Autowired
    private ForumLetterService forumLetterService;
    private final static Logger logger = LoggerFactory.getLogger(MemberVipExchangeNoticeListener.class);

    @Override
    public void onMessage(Message<MemberVipExchangeEvent> message) throws RetryableMessageException {
        logger.info("[Member][VipExchangeEvent][2]VIP会员开通通知开始发送");
        MemberVipExchangeRecords ver = message.getPayload().getRecord();
        forumLetterService.create(
                getVipGroupNotic(ver.getMemberNickname(), ver.getActiveDateTime(), ver.getDuration(), ver.getDurationUnit()),
                List.of(new ForumLetterReceiver(ver.getMemberId(), ver.getMemberNickname())));
        logger.info("[Member][VipExchangeEvent][2]VIP会员开通通知发送结束");
    }

    private ForumLetter getVipGroupNotic(String memberNickname, LocalDateTime activeDateTime, int duration, ForumCalendarUnitEnum durationUnit) {
        return ForumLetter.noticeLetter(
                "VIP会员开通通知",
                String.format("恭喜您: %s, 您的VIP身份从%s开始，有效期: %d(%s)! 如果存在异议您可以联系在线管理员", memberNickname, DateTimeUtils.getRFC3339(activeDateTime), duration, durationUnit.getTitle()));
    }

}
