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

import java.util.Comparator;
import java.util.Optional;
import java.util.TreeMap;
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.SmileyThemeDao;
import com.apobates.forum.core.api.service.SmileyThemeService;
import com.apobates.forum.core.entity.SmileyTheme;

@Service
public class SmileyThemeServiceImpl implements SmileyThemeService{
	@Autowired
	private SmileyThemeDao smileyThemeDao;

	@Override
	public Optional<SmileyTheme> get(int id) {
		if(id>0) {
			return smileyThemeDao.findOne(id);
		}
		return Optional.empty();
	}

	@Override
	public Optional<SmileyTheme> getByDirectName(String themeDirectName) {
		return smileyThemeDao.findOneByDirectName(themeDirectName);
	}

	@Override
	public Optional<Boolean> edit(int id, SmileyTheme updateSmileTheme)throws IllegalStateException {
		SmileyTheme st = get(id).orElseThrow(()->new IllegalStateException("表情风格不存在"));
		st.setDirectNames(updateSmileTheme.getDirectNames());
		st.setLabel(updateSmileTheme.getLabel());
		st.setTitle(updateSmileTheme.getTitle());
		st.setStatus(updateSmileTheme.isStatus());
		return smileyThemeDao.edit(st);
	}

	@Override
	public Stream<SmileyTheme> getAll() {
		return smileyThemeDao.findAll();
	}

	@Override
	public Optional<SmileyTheme> create(String title, String label, String directNames, boolean status, int ranking)throws IllegalStateException {
		SmileyTheme st = new SmileyTheme(title, label, directNames, status, ranking);
		try {
			smileyThemeDao.save(st);
			if(st.getId()>0) {
				return Optional.of(st);
			}
		}catch(Exception e) {
			throw new IllegalStateException(e.getMessage());
		}
		throw new IllegalStateException("表情风格创建失败");
	}

	@Override
	public TreeMap<String, String> getAllUsed() {
		return getAll()
				.filter(st -> st.isStatus())
				.sorted(Comparator.comparingInt(SmileyTheme::getRanking))
				.collect(Collectors.toMap(
							SmileyTheme::getDirectNames, 
							SmileyTheme::getTitle, 
							(oldSmileyThemeTitle, newSmileyThemeTitle) -> newSmileyThemeTitle, 
							TreeMap::new));
	}
}
