package org.jeecg.modules.adweb.common.util;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;

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

/** 英文分词器 */
public class EnglishAnalyzer {

    public static List<String> analyze(String text, Analyzer analyzer) throws IOException {
        List<String> result = new ArrayList<>();
        TokenStream tokenStream = analyzer.tokenStream("", text);
        CharTermAttribute attr = tokenStream.addAttribute(CharTermAttribute.class);
        tokenStream.reset();
        while (tokenStream.incrementToken()) {
            result.add(attr.toString());
        }
        return result;
    }

    public static int getLongestSize(String text) {
        if (StringUtils.isEmpty(text)) {
            return 0;
        }

        List<String> result;
        try {
            result = analyze(text, new StandardAnalyzer());
        } catch (Exception e) {
            return 0;
        }

        if (CollectionUtils.isEmpty(result)) {
            return 0;
        }

        return result.stream().mapToInt(String::length).max().getAsInt();
    }
}
