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

import com.apobates.forum.core.entity.Posts;
import com.apobates.forum.core.entity.TopicConfig;
import com.apobates.forum.member.entity.Member;
import com.apobates.forum.strategy.StrategyMode;
import com.apobates.forum.strategy.exception.StrategyException;
import com.apobates.forum.strategy.exposure.config.ConfigPlugBiPredicate;
import java.util.function.BiPredicate;
import java.util.function.Supplier;
import java.util.stream.Stream;

/**
 * 话题回复不间断操作补充策略
 * 
 * @author xiaofanku
 * @since 20200806
 */
public final class TopicConfigInterruptStrategy implements ConfigPlugBiPredicate<TopicConfig, Member>{
    private final Supplier<Stream<Posts>> recentReplies;
    
    public TopicConfigInterruptStrategy(Supplier<Stream<Posts>> recentReplies) {
        this.recentReplies = recentReplies;
    }
    
    @Override
    public Supplier<BiPredicate<TopicConfig, Member>> condition() {
        return ()->(TopicConfig entityConfig, Member culpritor)->{
            int wmiSize = entityConfig.getWriteMinInterrupt();
            long member = culpritor.getId();
            
            if (wmiSize > 0) {
                long statsData = recentReplies.get().filter(p -> p.getMemberId() == member).count();
                if (statsData >= wmiSize) {
                    throw new StrategyException("话题连续操作次数设置导致回复被中断");
                }
            }
            return true;
        };
    }
    
    @Override
    public StrategyMode[] allowModes(){
        return new StrategyMode[]{StrategyMode.WRITE};
    }
}