package cn.com.capcloud.core.lucene;

import org.apache.lucene.store.FSDirectory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Configuration
public class LuceneConfig {
    @Value("${lucene.index.dir}")
    private String indexDir;

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Bean
    public Map<String,LuceneInfo> indexDirectory() throws IOException {
        //todo data_source saveBefore 需要重新初始化
        List<Map<String, Object>> dataSourceList=jdbcTemplate.queryForList("select * from tbl_data_source where status=0 and is_lucene='Y'");
        Map<String,LuceneInfo> luceneInfoMap=new HashMap<>();
        for (int i = 0; i < dataSourceList.size(); i++) {
            Map<String, Object> dataSourceMap=dataSourceList.get(i);
            LuceneInfo luceneInfo=new LuceneInfo();
            String tableName=String.valueOf(dataSourceMap.get("ds_table_name"));
            luceneInfo.setDirectory(FSDirectory.open(Paths.get(indexDir+tableName)));
            luceneInfo.setAnalyzer(new IKAnalyzer4Lucene7());
            luceneInfoMap.put(tableName,luceneInfo);
        }
        return luceneInfoMap;
    }
}
