package com.pcloud.book.es.biz.impl;

import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

/**
 * 分词工具
 */
public class IKAnalyzerUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(IKAnalyzerUtil.class);

    /**
     * 通配符
     */
    public static final char WILDCARD_CHAR = '*';

    /**
     * 前后加通配符
     * @param text  内容
     * @return
     */
    public static String aroundWildcard(String text) {
        return WILDCARD_CHAR + text + WILDCARD_CHAR;
    }

    /**
     * 解析成分词后通配字符串
     * @param text  内容
     * @return  String，*通配
     */
    public static String parseWildcardString(String text) {
        if (StringUtils.isBlank(text)) {
            return text;
        }
        return StringUtils.join(analyzerText(text), WILDCARD_CHAR);
    }

    /**
     * 分词
     * @param text   内容
     * @return  List<分词>
     */
    public static List<String> analyzerText(String text) {
        List<String> result = new ArrayList<>();

        TokenStream ts = null;
        try (IKAnalyzer analyzer = new IKAnalyzer(true)) {
            ts = analyzer.tokenStream("text", new StringReader(text));
            CharTermAttribute term = ts.addAttribute(CharTermAttribute.class);
            ts.reset();

            while (ts.incrementToken()) {
                result.add(term.toString());
            }

            ts.end();
        } catch (IOException ioe) {
            result.add(text);
            LOGGER.warn("analyzer text exception,text={}", text, ioe);
        } finally {
            closeTokenStream(text, ts);
        }
        return result;
    }

    private static void closeTokenStream(String text, TokenStream ts) {
        if (ts != null) {
            try {
                ts.close();
            } catch (IOException ioe) {
                LOGGER.warn("analyzer text, close stream exception,text={}", text, ioe);
            }
        }
    }
}
