package com.apobates.forum.thrones.event;

import com.apobates.forum.event.utils.IpMatchResult;
import com.apobates.forum.event.utils.IpMatcher;
import java.time.LocalDateTime;
import java.util.List;
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 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.dao.MemberActiveRecordsDao;
import com.apobates.forum.member.entity.Member;
import com.apobates.forum.member.entity.MemberActiveRecords;
import com.apobates.forum.member.impl.event.MemberSignInEvent;
import com.apobates.forum.utils.DateTimeUtils;
import org.springframework.stereotype.Component;
import java.util.Optional;

/**
 * 会员登录事件侦听器,异地登录通知
 *
 * @author xiaofanku
 * @since 20190703
 */
@Component("loginNotice")
public class MemberSignInNoticeListener implements MessageListener<MemberSignInEvent> {
    @Autowired
    private ForumLetterService forumLetterService;
    @Autowired
    private MemberActiveRecordsDao memberActiveRecordsDao;
    private final static Logger logger = LoggerFactory.getLogger(MemberSignInNoticeListener.class);

    @Override
    public void onMessage(Message<MemberSignInEvent> event) throws RetryableMessageException {
        logger.info("[Member][SignInEvent][1]登录成功开始执行IP地域对比");
        MemberSignInEvent mse = event.getPayload();
        Member m = mse.getMember();
        String ipAddr = mse.getIpAddr();
        if (IpMatcher.isLoopbackIp(ipAddr)) {
            return; //环回地址不通知
        }
        List<MemberActiveRecords> rs = memberActiveRecordsDao.findAllByMemberNames(m.getNames(), 2).collect(Collectors.toList());
        if (rs.size() != 2) {
            return; //不满足判断条件
        }
        Optional<IpMatchResult> mr = IpMatcher.getInstance().matchToResult(ipAddr);
        if (!mr.isPresent()) {
            return; //没有可供比较的值
        }
        String p = mr.get().getProvince();
        String c = mr.get().getCity();
        long matchCount = rs.stream().filter(mar -> mar.getProvince().equals(p) && mar.getCity().equals(c)).count();
        //是否是异地
        if (matchCount == 1) {
            forumLetterService.create(
                    getLoginAbnormalNotic(m.getNames(), LocalDateTime.now(), p.concat(c)),
                    List.of(new ForumLetterReceiver(m.getId(), m.getNickname())));
        }
        logger.info("[Member][SignInEvent][1]IP地域对比结束");
    }
    
    //登录时IP变更
    private ForumLetter getLoginAbnormalNotic(String names, LocalDateTime loginDateTime, String requestAddress) {
        return ForumLetter.noticeLetter(
                "异地登录通知",
                String.format("亲爱的:%s, 您的帐户于%s在%s完成了登录, 若非本人操作请注意您的帐户安全", names, DateTimeUtils.getRFC3339(loginDateTime), requestAddress));
    }
}