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

import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import com.apobates.forum.core.api.dao.TopicTagDao;
import com.apobates.forum.core.api.service.TopicTagService;
import com.apobates.forum.core.entity.TopicTag;
import com.apobates.forum.event.elderly.ActionDescriptor;
import com.apobates.forum.event.elderly.ActionEventCulpritor;
import com.apobates.forum.event.elderly.ForumActionEnum;
import com.apobates.forum.utils.persistence.Page;
import com.apobates.forum.utils.persistence.Pageable;

@Service
public class TopicTagServiceImpl implements TopicTagService{
	@Autowired
	private TopicTagDao topicTagDao;
	
	@Cacheable(value="topicCache", key="'tag_'+#topicId")
	@Override
	public List<TopicTag> getAllBy(long topicId) {
		return topicTagDao.findAllByTopic(topicId);
	}
	
	@ActionDescriptor(action=ForumActionEnum.TOPIC_TAG_DEL)
	@CacheEvict(value="topicCache", key="'tag_'+#topicId")
	@Override
	public Optional<Boolean> deleteForTopic(long topicId, long tagId, ActionEventCulpritor culpritor)throws IllegalStateException {
		return topicTagDao.remove(tagId, topicId);
	}
	
	@ActionDescriptor(action=ForumActionEnum.TOPIC_TAG_ADD)
	@CacheEvict(value="topicCache", key="'tag_'+#topicId")
	@Override
	public Optional<Boolean> addForTopic(long topicId, Map<String,Integer> tagsData, ActionEventCulpritor culpritor)throws IllegalStateException {
		int affect = 0;
		try{
			affect = topicTagDao.batchSave(topicId, tagsData);
		}catch(Exception e){
			throw new IllegalStateException(e.getMessage());
		}
		return affect == tagsData.size()?Optional.of(true):Optional.empty();
	}

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

	@Override
	public Map<String, Long> groupTagForNames(int size) {
		return topicTagDao.groupTagForNames(size);
	}
	
	@ActionDescriptor(action=ForumActionEnum.TOPIC_TAG_ADD, isRedress=false)
	@CacheEvict(value="topicCache", key="'tag_'+#topicId")
	@Override
	public long create(long topicId, String names, int rates, ActionEventCulpritor culpritor)throws IllegalStateException {
		TopicTag tt = new TopicTag(names, rates, topicId);
		try{
			topicTagDao.save(tt);
			if(tt.getId()>0){
				return tt.getId();
			}
		}catch(Exception e){
			throw new IllegalStateException(e.getMessage());
		}
		throw new IllegalStateException("新增标签操作失败");
	}
}
