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

import com.mayabot.nlp.segment.FluentLexerBuilder;
import com.mayabot.nlp.segment.Lexer;
import com.mayabot.nlp.segment.Lexers;
import com.mayabot.nlp.segment.Sentence;
import net.northking.cctp.scriptcase.api.nlp.service.MuteCustomDictionary;
import net.northking.cctp.scriptcase.api.nlp.service.NLPService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

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

    private Lexer lexer;
    @Autowired
    private MuteCustomDictionary dictionary;

    @PostConstruct
    public void init() {
        if (lexer == null) {
            FluentLexerBuilder builder = Lexers.coreBuilder().withPos().withPersonName();
            if (dictionary != null) {
                builder.withCustomDictionary(dictionary);
            }
            lexer = builder.build();
        }
        logger.info("NLP组件初始化成功");
    }

    @Override
    public List<String> getWordList(String text) {
        logger.debug("待分词对象：{}",text);
        List<String> list = new ArrayList<>();
        if (StringUtils.hasText(text)) {
            dictionary.rebuild();
            Sentence sentence = lexer.scan(text);
            list = sentence.toWordList();
        }
        return list;
    }
}
