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

import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import com.apobates.forum.core.api.dao.TopicConfigDao;
import com.apobates.forum.core.api.service.TopicConfigService;
import com.apobates.forum.core.entity.TopicConfig;

@Service
public class TopicConfigServiceImpl implements TopicConfigService{
	@Autowired
	private TopicConfigDao topicConfigDao;
	
	@Cacheable(value="topicCache", key="'topic_config_'+#topicId", unless="#result==null")
	@Override
	public Optional<TopicConfig> getByTopicId(long topicId) { //[TC]T2
		return topicConfigDao.findOneByTopic(topicId);
	}

	@Override
	public Optional<Boolean> create(long topicId, TopicConfig config)throws IllegalStateException {
		try {
			config.setTopicId(topicId);
			topicConfigDao.save(config);
			if(config.getId()>0){
				return Optional.of(true);
			}
			return Optional.empty();
		}catch(Exception e) {
			throw new IllegalStateException(e.getMessage());
		}
	}
}
