package com.apobates.forum.strategy.exposure.supply;

import com.apobates.forum.event.elderly.ForumActionEnum;
import com.apobates.forum.member.entity.Member;
import com.apobates.forum.member.entity.MemberGroupEnum;
import com.apobates.forum.strategy.exception.VerificaFailException;
import com.apobates.forum.utils.DateTimeUtils;
import java.time.LocalDateTime;
import java.util.function.BiPredicate;

/**
 * 会员冰封期扩展检测器
 * 
 * @author xiaofanku
 * @since 20200806
 */
public final class FreezePlugStrategy implements BiPredicate<Member, ForumActionEnum>{
    private final int newMemberFreezeMinute;
    
    public FreezePlugStrategy(int newMemberFreezeMinute) {
        this.newMemberFreezeMinute = newMemberFreezeMinute;
    }
    
    @Override
    public boolean test(Member member, ForumActionEnum action) {
        try {
            if (isFreeze(newMemberFreezeMinute, member.getMgroup(), member.getRegisteDateTime())) {
                throw new VerificaFailException(String.format("新注册的会员在冰封期不可以%s", action.getTitle()));
            }
        } catch (NullPointerException e) {
            throw new VerificaFailException(String.format("暂不支持匿名会员进行:%s", action.getTitle()));
        }
        return true;
    }
    /**
     * 新注册的会员是否在冰封期
     *
     * @param freezeMinute 系统设定的冻结分钟数
     * @return true处于冰封期,false不处于
     */
    private boolean isFreeze(int freezeMinute, MemberGroupEnum mgroup, LocalDateTime registerDateTime) {
        //游客判断
        if (MemberGroupEnum.GUEST == mgroup) {
            throw new NullPointerException();
        }
        //不进行冰封期检查
        if (freezeMinute == 0) {
            return false;
        }
        //VIP 和管理员不冰封
        if (MemberGroupEnum.VIP == mgroup || MemberGroupEnum.LEADER == mgroup) {
            return false;
        }
        long diffMin = DateTimeUtils.diffMinutes(LocalDateTime.now(), registerDateTime);
        return diffMin <= freezeMinute;
    }
}