using Lucene.Net.Analysis.PanGu;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Search;
using Lucene.Net.Store;
using PanGu;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using LuceneNet.Models;

namespace LuceneNet.Filters
{
    /// <summary>
    /// 索引文件类
    /// </summary>
    public class LuceneIndexModifier
    {
        /// <summary>
        /// 创建索引文件或添加索引
        /// </summary>
        /// <param name="indexPath"> 索引文件目录 indexPath =AppDomain.CurrentDomain.BaseDirectory + "IndexData2"; </param>
        public static void saveIndex(string indexPath = "")
        {
            indexPath = indexPath == "" ? AppDomain.CurrentDomain.BaseDirectory + "IndexData2" : indexPath;
            FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexPath), new NativeFSLockFactory());
            // IndexReader:对索引库进行读取的类
            bool isExist = IndexReader.IndexExists(directory); //是否存在索引库文件夹以及索引库特征文件
            if (isExist)
            {
                //如果索引目录被锁定（比如索引过程中程序异常退出或另一进程在操作索引库），则解锁
                //Q:存在问题 如果一个用户正在对索引库写操作 此时是上锁的 而另一个用户过来操作时 将锁解开了 于是产生冲突 --解决方法后续
                if (IndexWriter.IsLocked(directory))
                {
                    IndexWriter.Unlock(directory);
                }
            }
            //使用PanGuAnalyzer初始化IndexWriter，参数create为true表示创建，为false表示添加。
            IndexWriter writer = new IndexWriter(directory, new PanGuAnalyzer(), !isExist, IndexWriter.MaxFieldLength.UNLIMITED);
            //添加Field
            List<Books> BooksList = new List<Books>();
            
            foreach (var a in BooksList)
            {
                Document document = new Document();//创建Document
                document.Add(new Field("id", a.Id.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
                Field title = new Field("title", a.Title, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS);
                //Field title = new Field("title", a.Title, Field.Store.YES, Field.Index.NOT_ANALYZED);
                title.SetBoost(10F);
                document.Add(title);
                Field content = new Field("content", a.ContentDescription, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS);
                // content.SetBoost(0.1F);
                document.Add(content);
                writer.AddDocument(document);//向索引添加文档
            }
            writer.Optimize();//优化索引
            writer.Close();//关闭索引
            directory.Close(); //不要忘了Close，否则索引结果搜不到
        }
    }
}