package com.apobates.forum.core.impl.service;

import com.apobates.forum.core.dao.BoardStatsDao;
import com.apobates.forum.core.dao.TopicDao;
import com.apobates.forum.core.entity.BoardStats;
import com.apobates.forum.core.service.BoardStatsService;
import com.apobates.forum.event.elderly.ForumActionEnum;
import com.apobates.forum.utils.DateTimeUtils;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Stream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 *
 * @author xiaofanku
 * @since 20200513
 */
@Service
public class BoardStatsServiceImpl implements BoardStatsService{
    @Autowired
    private BoardStatsDao boardStatsDao;
    @Autowired
    private TopicDao topicDao;
    
    @Override
    public Stream<BoardStats> getFillTodayTopices(int boardGroupId) {
        return foldTodayTopices(boardStatsDao.findAllByBoardGroup(boardGroupId));
    }
    
    @Override
    public Stream<BoardStats> getFillTodayTopicesForNotOrigin() {
        return foldTodayTopices(boardStatsDao.findAllForNotOriginBoard());
    }
    
    @Override
    public Stream<BoardStats> getFillTodayTopices(Set<Long> boardIdSet) {
        if (null == boardIdSet || boardIdSet.isEmpty()) {
            return Stream.empty();
        }
        return foldTodayTopices(boardStatsDao.findAllByBoardId(boardIdSet));
    }
    
    @Override
    public Stream<BoardStats> getAll() {
        return boardStatsDao.findAll();
    }
    
    @Override
    public Stream<BoardStats> getByBoardIdList(Set<Long> boardIdList) {
        if (null == boardIdList || boardIdList.isEmpty()) {
            return Stream.empty();
        }
        return boardStatsDao.findAllByBoardId(boardIdList);
    }
    
    @Override
    public Optional<BoardStats> getByBoard(long boardId) {
        return boardStatsDao.findOneByBoard(boardId);
    }
    
    @Override
    public Map<ForumActionEnum, Long> sumTopicAndPosts() {
        return boardStatsDao.sumTopicAndPosts();
    }
    private Stream<BoardStats> foldTodayTopices(Stream<BoardStats> rs){
         Map<Long, Long> todayTopices = topicDao.statsBoardTopicSize(DateTimeUtils.getTodayEarlyMorning(), DateTimeUtils.getTodayMidnight());
        return rs.peek(bs->{
            try {
                Long t = todayTopices.get(bs.getBoardId());
                bs.setTodayTopices(null == t ? 0L : t);
            } catch (NullPointerException e) {}
        });
    }
}