package net.northking.cctp.scriptcase.api.nlp.service;

import com.mayabot.nlp.algorithm.collection.dat.DoubleArrayTrieStringIntMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.TreeMap;

@Service
public class RedisCustomDictionary implements MuteCustomDictionary {
    /**
     * 日志
     */
    private final static Logger logger = LoggerFactory.getLogger(RedisCustomDictionary.class);

    @Autowired
    private StringRedisTemplate redisTemplate;
    private DoubleArrayTrieStringIntMap trie;
    private TreeMap<String,Integer> dict = new TreeMap<>();

    @Override
    public void rebuild() {
        if (needUpdate()) {
            Map<Object,Object> dictMap = redisTemplate.opsForHash().entries(KEY_NLP_CUSTOM_DICT);
            if (dictMap.isEmpty()) {
                this.trie = null;
            } else {
                dict.clear();
                for (Map.Entry<Object, Object> entry : dictMap.entrySet()) {
                    dict.put((String) entry.getKey(),(Integer) entry.getValue());
                }
                this.trie = new DoubleArrayTrieStringIntMap(this.dict);
            }
        }

    }

    /**
     * 微服务多实例节点下判断是否需要更新
     * @return
     */
    private boolean needUpdate() {
        logger.debug("check custom ");
        Long len = redisTemplate.opsForHash().size(KEY_NLP_CUSTOM_DICT);
        int size = dict.size();
        int psize = 0;
        if (len != null) {
            psize = len.intValue();
        }
        return size == psize;
    }

    @Override
    public DoubleArrayTrieStringIntMap getTrie() {
        return this.trie;
    }
}
