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

import com.apobates.forum.core.entity.BoardModerator;
import com.apobates.forum.event.elderly.ForumActionEnum;
import com.apobates.forum.member.entity.Member;
import com.apobates.forum.member.entity.MemberRoleEnum;
import com.apobates.forum.strategy.exception.VerificaFailException;
import com.apobates.forum.utils.lang.TriPredicate;
import java.util.Arrays;
import java.util.Optional;
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.Stream;

/**
 * 版主身份扩展检测器
 * 
 * @author xiaofanku
 * @since 20200806
 */
public class ModeratorPlugStrategy implements TriPredicate<Member, ForumActionEnum, Set<MemberRoleEnum>>{
    private final Supplier<Stream<BoardModerator>> moderators;
    
    public ModeratorPlugStrategy(Supplier<Stream<BoardModerator>> moderators) {
        this.moderators = moderators;
    }
    
    @Override
    public boolean test(Member member, ForumActionEnum action, Set<MemberRoleEnum> allowRoles) {
        if (MemberRoleEnum.ADMIN == member.getMrole()) { //为管理员放行
            return true;
        }
        if (allowRoles.containsAll(Arrays.asList(MemberRoleEnum.BM, MemberRoleEnum.MASTER))) {
            //是否是本版块的版主
            if (moderators == null) { //没有设版主
                throw new VerificaFailException("您的管理权限被拦截");
            }
            Optional<Long> rs = moderators.get().map(BoardModerator::getMemberId).filter(mid -> mid == member.getId()).findFirst();
            if (!rs.isPresent()) {
                throw new VerificaFailException("您暂不具备当前对象的管理权限");
            }
        }
        return true;
    }
}