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

import java.util.Arrays;
import java.util.Optional;
import java.util.stream.Stream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.apobates.forum.core.api.dao.TopicCategoryDao;
import com.apobates.forum.core.api.service.TopicCategoryService;
import com.apobates.forum.core.entity.TopicCategory;
import com.apobates.forum.utils.Commons;
import com.apobates.forum.utils.persistence.Page;
import com.apobates.forum.utils.persistence.Pageable;

@Service
public class TopicCategoryServiceImpl implements TopicCategoryService{
	@Autowired
	private TopicCategoryDao topicCategoryDao;

	@Override
	public Page<TopicCategory> getAll(Pageable pageable) {
		return topicCategoryDao.findAll(pageable);
	}

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

	@Override
	public Optional<TopicCategory> create(String names, String value, boolean status)throws IllegalStateException {
		if(TopicCategory.isKeywords(value)){
			throw new IllegalStateException("属性值为保留词.不允许使用");
		}
		TopicCategory tc = new TopicCategory(value, names);
		tc.setStatus(status);
		try{
			topicCategoryDao.save(tc);
			
			if(tc.getId()>0) {
				return Optional.of(tc);
			}
		}catch(Exception e) {
			throw new IllegalStateException(e.getMessage());
		}
		throw new IllegalStateException("话题类型创建失败");
	}

	@Override
	public Optional<Boolean> remove(int id)throws IllegalStateException {
		TopicCategory data = get(id).orElseThrow(()->new IllegalStateException("话题类型不存在"));
		data.setStatus(false);
		return topicCategoryDao.edit(data);
	}

	@Override
	public Optional<Boolean> edit(int id, TopicCategory updateCategory)throws IllegalStateException {
		TopicCategory data = get(id).orElseThrow(()->new IllegalStateException("话题类型不存在"));
		data.setNames(updateCategory.getNames());
		//
		if(!TopicCategory.isKeywords(updateCategory.getValue())){
			data.setValue(updateCategory.getValue());
		}
		
		data.setStatus(updateCategory.isStatus());
		return topicCategoryDao.edit(data);
	}

	@Override
	public Stream<TopicCategory> getAllUsed() {
		return topicCategoryDao.findUsed();
	}

	@Override
	public Optional<TopicCategory> get(String value) {
		if(Commons.isNotBlank(value) || !TopicCategory.isKeywords(value)){
			return topicCategoryDao.findOneByValue(value);
		}
		return Optional.empty();
	}

	@Override
	public Stream<TopicCategory> getAssociates() {
		Stream<TopicCategory> usedCategories = topicCategoryDao.findUsed();
		return Stream.concat(usedCategories, Arrays.asList(TopicCategory.feedback(), TopicCategory.report()).stream());
	}

}
