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

import java.util.EnumMap;
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;
import com.apobates.forum.core.api.dao.BoardStatsDao;
import com.apobates.forum.core.api.dao.TopicDao;
import com.apobates.forum.core.api.service.BoardStatsService;
import com.apobates.forum.core.entity.BoardStats;
import com.apobates.forum.event.elderly.ForumActionEnum;
import com.apobates.forum.utils.DateTimeUtils;

@Service
public class BoardStatsServiceImpl implements BoardStatsService{
	@Autowired
	private BoardStatsDao boardStatsDao;
	@Autowired
	private TopicDao topicDao;
	
	@Override
	public Optional<BoardStats> getByBoard(long boardId) {
		return boardStatsDao.findOneByBoard(boardId);
	}

	@Override
	public Stream<BoardStats> getAll() {
		return boardStatsDao.findAll();
	}

	@Override
	public Stream<BoardStats> getByBoardIdList(Set<Long> boardIdList) {
		if(boardIdList==null || boardIdList.isEmpty()){
			return Stream.empty();
		}
		return boardStatsDao.findAllByBoardId(boardIdList);
	}

	@Override
	public EnumMap<ForumActionEnum, Long> sumTopicAndPosts() {
		try{
			return boardStatsDao.sumTopicAndPosts();
		}catch(Exception e){ //初次运行出现NPE
			return new EnumMap<>(ForumActionEnum.class);
		}
	}

	@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));
	}

	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) {
			}
		});
	}
}
