package cn.reghao.tnb.search.app.lucene;

import cn.reghao.tnb.search.app.model.po.VideoText;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;

/**
 * @author reghao
 * @date 2025-04-02 11:12:48
 */
@Service
public class LuceneDocument {
    public Object getObject(Class<?> clazz, Document document) throws Exception {
        Field[] fields = clazz.getDeclaredFields();
        Object object = clazz.getDeclaredConstructor().newInstance();
        for (int i = 0; i < fields.length; i++) {
            String name = fields[i].getName();
            String value = document.get(name);
            if (value == null) {
                continue;
            }

            Class<?> clazzType = fields[i].getType();
            if (clazzType.equals(String.class)) {
                fields[i].setAccessible(true);
                fields[i].set(object, value);
            } else {
                Object result = null;
                if (clazzType.equals(Long.class)) {
                    result = Long.parseLong(value);
                } else if (clazzType.equals(Double.class)) {
                    result = Double.parseDouble(value);
                } else if (clazzType.equals(Integer.class)) {
                    result = Integer.parseInt(value);
                } else if (clazzType.equals(Boolean.class)) {
                    result = Boolean.parseBoolean(value);
                }

                fields[i].setAccessible(true);
                fields[i].set(object, result);
            }
        }

        return object;
    }

    public Document getVideoTextDoc(VideoText videoText) {
        Document doc = new Document();
        doc.add(new StringField("id", videoText.getId(), org.apache.lucene.document.Field.Store.YES));
        doc.add(new StringField("videoId", videoText.getVideoId(), org.apache.lucene.document.Field.Store.YES));
        doc.add(new TextField("title", videoText.getTitle(), org.apache.lucene.document.Field.Store.YES));
        doc.add(new TextField("description", videoText.getDescription(), org.apache.lucene.document.Field.Store.NO));
        doc.add(new StringField("scope", ""+videoText.getScope(), org.apache.lucene.document.Field.Store.YES));
        return doc;
    }
}
