package com.apobates.forum.core.entity.proxy;

import com.apobates.forum.core.entity.Board;
import com.apobates.forum.core.entity.BoardGroup;
import com.apobates.forum.utils.Commons;
import com.apobates.forum.utils.lang.ForumReplicable;
import java.util.Comparator;
import java.util.Objects;
import java.util.Optional;
import java.util.TreeSet;
import java.util.function.Function;
import java.util.regex.PatternSyntaxException;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author xiaofanku
 * @since 20200513
 */
public final class BoardGroupReplica extends BoardGroup implements ActiveDirectoryConnector<BoardGroupReplica>, ForumReplicable<BoardGroup, BoardGroupReplica>{
    //组下的版块
    private TreeSet<BoardReplica> boardes = new TreeSet<>();
    private final static Logger logger = LoggerFactory.getLogger(BoardGroupReplica.class);
    public static Function<BoardGroup,BoardGroupReplica> copyBoardGroup = (BoardGroup boardGroup)->{
        return ForumReplicable.replica(boardGroup, BoardGroupReplica.class).orElseGet(BoardGroupReplica::new);
    };
    
    public BoardGroupReplica() {
        super();
    }
    
    public static Optional<BoardGroupReplica> of(String connectValue){
        try{
            return new BoardGroupReplica().toConnector(connectValue);
        }catch(IllegalStateException e){
            return Optional.empty();
        }
    }
    //
    public void setBoards(Stream<BoardReplica> boards){
        this.boardes = boards.collect(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparingInt(BoardReplica::getRanking))));
    }
    public void pushBoards(TreeSet<Board> boards){
        TreeSet<BoardReplica> rs = boards.stream().map(BoardReplica.copyBoard).filter(Objects::nonNull).collect(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparingInt(BoardReplica::getRanking))));
        this.boardes.addAll(rs);
    }
    public TreeSet<BoardReplica> getBoardes() {
        return boardes;
    }
    //
    @Override
    public String getConnect() {
        return getId()+"";
    }
    
    @Override
    public Optional<BoardGroupReplica> toConnector(String connectValue) throws IllegalStateException {
        String[] params = {};
        try {
            params = connectValue.split("-");
        } catch (NullPointerException | PatternSyntaxException e) {
            throw new IllegalStateException("构造版块组的ActiveDirectoryConnector实例参数不合法");
        }
        if (params.length != 1) {
            throw new IllegalStateException("构造版块组的ActiveDirectoryConnector实例失败");
        }
        BoardGroupReplica boardGroup = new BoardGroupReplica();
        boardGroup.setId(Commons.stringToInteger(params[0], -1));
        return Optional.of(boardGroup);
    }
}