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

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.apobates.forum.core.api.dao.BoardModeratorActionIndexDao;
import com.apobates.forum.core.api.service.BoardModeratorActionIndexService;
import com.apobates.forum.core.entity.BoardModeratorActionIndex;
import com.apobates.forum.event.elderly.ForumActionEnum;

@Service
public class BoardModeratorActionIndexServiceImpl implements BoardModeratorActionIndexService{
	@Autowired
	private BoardModeratorActionIndexDao boardModeratorActionIndexDao;
	
	@Override
	public Stream<ForumActionEnum> getAllByBoardId(long moderatorId) {
		return boardModeratorActionIndexDao.getAllByModerator(moderatorId).map(BoardModeratorActionIndex::getAction).distinct();
	}

	@Override
	public Optional<Boolean> grantModeratorActions(final long moderatorId, List<ForumActionEnum> actions)throws IllegalStateException {
		if(actions == null || actions.isEmpty()){
			throw new IllegalStateException("参数不合法或不被接受");
		}
		List<BoardModeratorActionIndex> bmActions = actions.stream().map(fae -> new BoardModeratorActionIndex(moderatorId, fae)).collect(Collectors.toList());
		try {
			boardModeratorActionIndexDao.batchSave(bmActions);
			return Optional.of(true);
		}catch(Exception e) {
			throw new IllegalStateException(e.getMessage());
		}
	}

	@Override
	public Optional<Boolean> edit(long moderatorId, List<ForumActionEnum> actions)throws IllegalStateException{
		if(actions == null || actions.isEmpty()){
			throw new IllegalStateException("参数不合法或不被接受");
		}
		int affect = boardModeratorActionIndexDao.edit(moderatorId, actions);
		if(affect>0){
			return Optional.of(true);
		}
		throw new IllegalStateException("操作失败");
	}

}
