package org.nl.config.lucene;
/**
 * @author ldjun
 * @version 1.0
 * @date 2023年08月24日 13:00
 * @desc desc
 */

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import com.alibaba.ttl.TransmittableThreadLocal;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.*;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.IOException;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class LuceneAppender extends AppenderBase<ILoggingEvent> {

    public static final TransmittableThreadLocal<String> traceIdTL = new TransmittableThreadLocal();
    public LuceneProperties properties;
    public static Directory index;
    private List<LucenePropertyAndEncoder>  encoders;
    public static IndexWriter indexWriter;



    @Override
    public void start() {
        super.start();
        try {
            // 读取配置文件
            Properties properties = org.nl.acs.utils.YmlConfigFileUtil.readConfig("config/application.yml");

            // 获取配置值
            String luceneDir = properties.getProperty("lucene.index.path");
            System.out.println("---index地址----"+luceneDir);
            index = FSDirectory.open(Paths.get(luceneDir));
            // 初始化 Lucene 索引
            Analyzer analyzer = new IKAnalyzer();
            IndexWriterConfig config = new IndexWriterConfig(analyzer);
            indexWriter = new IndexWriter(index, config);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void append(ILoggingEvent event) {
        Document doc = new Document();
        for (Property property : this.properties.getProperties()) {
            LucenePropertyAndEncoder encoder = new LucenePropertyAndEncoder(property, this.context);
            String encode = encoder.encode(event);
            doc.add(new StringField(property.getName(), encode, Field.Store.YES));
        }
        Map<String, String> map = event.getMDCPropertyMap();
        if (!map.isEmpty() && StringUtils.isNotEmpty(map.get("traceId"))){
            doc.add(new StringField("traceId",map.get("traceId"), Field.Store.YES));
        }else {
            doc.add(new StringField("traceId"," ", Field.Store.YES));
        }

        doc.add(new TextField(LogMessageConstant.FIELD_MESSAGE, event.getFormattedMessage(), Field.Store.YES));
        doc.add(new StringField(LogMessageConstant.FIELD_TIMESTAMP, String.valueOf(event.getTimeStamp()),Field.Store.YES));
        doc.add(new NumericDocValuesField(LogMessageConstant.SORT_NAME, event.getTimeStamp()));
        try {
            indexWriter.addDocument(doc);
            indexWriter.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void stop() {
        super.stop();
        try {
            indexWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void setProperties(LuceneProperties properties) {
        this.properties = properties;

    }
}
