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

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
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.attention.core.ImagePathCoverter;
import com.apobates.forum.core.api.ImageIOMeta;
import com.apobates.forum.core.api.dao.AlbumDao;
import com.apobates.forum.core.api.dao.AlbumPictureDao;
import com.apobates.forum.core.api.service.AlbumService;
import com.apobates.forum.core.api.service.BoardService;
import com.apobates.forum.core.entity.Album;
import com.apobates.forum.core.entity.AlbumPicture;
import com.apobates.forum.core.entity.Board;
import com.apobates.forum.core.entity.Topic;
import com.apobates.forum.utils.persistence.Page;
import com.apobates.forum.utils.persistence.Pageable;

@Service
public class AlbumServiceImpl implements AlbumService{
	@Autowired
	private AlbumDao albumDao;
	@Autowired
	private AlbumPictureDao albumPictureDao;
	@Autowired
	private BoardService boardService;
	
	@Override
	public Page<Album> getAll(Pageable pageable) {
		return albumDao.findAll(pageable);
	}

	@Override
	public Page<Album> getAll(int volumesId, Pageable pageable) {
		return albumDao.findAllByVolumes(volumesId, pageable);
	}

	@Override
	public Page<Album> getAll(long boardId, Pageable pageable) {
		return albumDao.findAllByBoard(boardId, pageable);
	}

	@Override
	public Optional<Album> getByTopic(long topicId) {
		return albumDao.findOneByTopic(topicId);
	}

	@Override
	public Optional<Album> get(long id) {
		return albumDao.findOne(id);
	}

	@Override
	public Stream<Album> getAll(Set<Long> topicIdSet, ImageIOMeta imageIO, String scale, String defaultPicture) {
		if(topicIdSet == null || topicIdSet.isEmpty()){
			return Stream.empty();
		}
		List<Long> topicIds = topicIdSet.stream().filter(topicId -> topicId > 0).collect(Collectors.toList());
		Consumer<Album> action = album->{
			String imagePath = new ImagePathCoverter(album.getCoverLink())
					.decodeUploadImageFilePath(imageIO.getImageBucketDomain(), imageIO.getUploadImageDirectName(), scale)
					.orElse(defaultPicture); //"/static/img/140x140.png"
			album.setCoverLink(imagePath);
		};
		
		return albumDao.findAllByTopic(topicIds).peek(action);
	}

	@Override
	public Stream<Album> getRecent(int size) {
		List<Album> data = albumDao.findAllRecent(size).collect(Collectors.toList());
		if (data.isEmpty()) {
			return Stream.empty();
		}
		Set<Long> boardIdSet = data.stream().map(Album::getBoardId).collect(Collectors.toSet());
		//设置像册所属的版块
		Map<Long, String> boardTitleMap = boardService.getAllById(boardIdSet);
		Consumer<Album> action = ar -> {
			String boardTitle = boardTitleMap.get(ar.getBoardId());
			Board b = new Board();
			b.setId(ar.getBoardId());
			b.setTitle(boardTitle);
			b.setVolumesId(ar.getVolumesId());
			ar.setBoard(b);
		};
		return data.stream().peek(action);
	}

	@Override
	public Optional<Boolean> editCover(long id, long pictureId)throws IllegalStateException {
		AlbumPicture ap = albumPictureDao.findOne(pictureId).orElseThrow(()->new IllegalStateException("图片不存在或暂时无法访问"));
		if(!ap.isStatus()){
			throw new IllegalStateException("图片已被禁止访问");
		}
		
		return albumDao.editCover(id, ap.getLink(), ap.getId());
	}

	@Override
	public long create(String encodeImageAddr, String caption, boolean status, Topic topic)throws IllegalStateException {
		if(encodeImageAddr == null || encodeImageAddr.isEmpty()){
			throw new IllegalStateException("图片地址不可用或不被接受");
		}
		AlbumPicture ap = new AlbumPicture();
		ap.setStatus(status);
		ap.setLink(encodeImageAddr);
		ap.setCaption(caption);
		
		Album album = new Album(
				topic.getTitle(), 
				topic.getVolumesId(), 
				topic.getBoardId(), 
				topic.getId(), 
				topic.getMemberId(), 
				topic.getMemberNickname(), 
				Arrays.asList(ap));
		ap.setAlbum(album);
		try{
			albumDao.save(album);
			if(album.getId()>0){
				//话题是否有像册了
				if(topic.getAlbumId() == 0){
					albumDao.bindTopicAlbum(album.getId(), topic.getId());
				}
				return album.getId();
			}
		}catch(Exception e){
			throw new IllegalStateException(e.getMessage());
		}
		throw new IllegalStateException("像册创建失败");
	}

}
