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

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

/**
 *
 * @author xiaofanku
 * @since 20200513
 */
@Service
public class TopicTagServiceImpl implements TopicTagService{
    @Autowired
    private TopicTagDao topicTagDao;
    private final static Logger logger = LoggerFactory.getLogger(TopicTagServiceImpl.class);
    
    @Cacheable(value="topicCache", key="'tag_'+#topicId")
    @Override
    public List<TopicTag> getAllBy(long topicId) {
        return topicTagDao.findAllByTopic(topicId);
    }
    
    @CacheEvict(value="topicCache", key="'tag_'+#topicId")
    @Override
    public Optional<Boolean> deleteForTopic(long topicId, long tagId, ActionEventCulpritor culpritor) {
        return topicTagDao.remove(tagId, topicId);
    }
    
    @CacheEvict(value="topicCache", key="'tag_'+#topicId")
    @Override
    public Optional<Boolean> addForTopic(long topicId, Map<String, Integer> tagData, ActionEventCulpritor culpritor) {
        int affect = topicTagDao.batchSave(topicId, tagData);
        return affect == tagData.size() ? Optional.of(true) : Optional.empty();
    }
    
    @CacheEvict(value="topicCache", key="'tag_'+#topicId")
    @Override
    public long create(long topicId, String names, int rates, ActionEventCulpritor culpritor) {
        TopicTag tt = new TopicTag(names, rates, topicId);
        try{
            topicTagDao.save(tt);
            if (tt.getId() > 0) {
                return tt.getId();
            }
        }catch(Exception e){
            if(logger.isDebugEnabled()){
                logger.debug("新增标签操作失败", e);
            }
        }
        return 0L;
    }
    @Override
    public Page<TopicTag> getAll(Pageable pageable) {
        return topicTagDao.findAll(pageable);
    }
    
    @Override
    public Map<String, Long> groupTagForNames(int size) {
        return topicTagDao.groupTagForNames(size);
    }
}