package org.diagbot.nlp.feature;

import org.diagbot.nlp.feature.extract.CaseToken;
import org.diagbot.nlp.feature.extract.CaseTokenFactory;
import org.diagbot.nlp.participle.ParticipleUtil;
import org.diagbot.nlp.participle.word.Lexeme;
import org.diagbot.nlp.participle.word.LexemePath;
import org.diagbot.nlp.util.Constants;
import org.diagbot.nlp.util.NlpCache;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class FeatureAnalyze {
    private LexemePath<Lexeme> lexemePath = null;

    public List<Map<String, Object>> start(String content, FeatureType featureType) throws Exception {
        CaseToken caseToken = createCaseToken(featureType);
        return this.extract(caseToken, content);
    }

    public Map<String, List<Map<String, Object>>> start(String rdn, String content, FeatureType featureType) throws Exception {
        CaseToken caseToken = createCaseToken(featureType);
        long start = System.currentTimeMillis();
        Map<String, List<Map<String, Object>>> featuresMap = new HashMap<>();
        featuresMap.put(rdn, this.extract(caseToken, content));
        long end = System.currentTimeMillis();
        System.out.println("提取特征词耗时........." + (end - start));
        return featuresMap;
    }

    public Map<String, List<Map<String, Object>>> start(Map<String, String> map, FeatureType featureType) throws Exception {
        CaseToken caseToken = createCaseToken(featureType);
        long start = System.currentTimeMillis();
        Map<String, List<Map<String, Object>>> featuresMap = new HashMap<>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            featuresMap.put(entry.getKey(), this.extract(caseToken, entry.getValue()));
        }
        long end = System.currentTimeMillis();
        System.out.println("提取特征词耗时........." + (end - start));
        return featuresMap;
    }

    public List<Map<String, Object>> extract(CaseToken caseToken, String content) throws Exception {
        if (StringUtils.isEmpty(content)) {
            return null;
        }
        lexemePath = ParticipleUtil.participle(content);
        lexemePath = replaceLexeme(lexemePath);
        return caseToken.analyze(lexemePath);
    }

    public CaseToken createCaseToken(FeatureType featureType) throws Exception {
        CaseToken caseToken = CaseTokenFactory.getInstance(featureType);
        return caseToken;
    }

    private LexemePath replaceLexeme(LexemePath<Lexeme> lexemePath) {
        if (NlpCache.standard_info_synonym_map == null) NlpCache.createSynonymCache();
        for (Lexeme l : lexemePath) {
            if (NlpCache.standard_info_synonym_map.get(l.getText()) != null) {
                l.setText(NlpCache.standard_info_synonym_map.get(l.getText()));
            }
        }
        return lexemePath;
    }
}
