package com.lerx.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.lucene.search.Query;
import org.hibernate.search.FullTextQuery;
import org.hibernate.search.FullTextSession;
import org.hibernate.search.Search;
import org.hibernate.search.exception.EmptyQueryException;
import org.hibernate.search.query.dsl.QueryBuilder;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

import com.lerx.dao.iface.ISearchTotalModelDao;
import com.lerx.entities.SearchTotalModel;
import com.lerx.hql.entities.Rs;
import com.lerx.hql.util.RsUtil;
import com.lerx.v6.util.SearchUtil;

public class SearchTotalModelDaoImpl extends HibernateDaoSupport implements ISearchTotalModelDao {

	@Override
	public SearchTotalModel add(SearchTotalModel srt) {
		this.getHibernateTemplate().save(srt);
		return srt;
	}

	@Override
	public void modify(SearchTotalModel srt) {
		this.getHibernateTemplate().update(srt);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Rs search(String key, boolean fulltext, int firstResult, int page, int pagesize) {
		
		FullTextSession fts = Search.getFullTextSession(this.getSessionFactory().getCurrentSession());
	    QueryBuilder qb = fts.getSearchFactory().buildQueryBuilder().forEntity(SearchTotalModel.class).get();
	    
	    Query luceneQuery;
	    List<SearchTotalModel> data;
	    Rs rs=null;
	    try {
			luceneQuery = qb.keyword().onFields("content","subject","subjectShort","synopsis","author","dept").matching(key).createQuery();
			
			FullTextQuery query = fts.createFullTextQuery(luceneQuery, SearchTotalModel.class);
			query.addQueryHint("status is true");
		    query.setFirstResult((page - 1) * pagesize);
		    query.setMaxResults(pagesize);
		    data = query.list();
		    rs=RsUtil.init(page, pagesize, query.getResultSize());
		    List<SearchTotalModel> la=SearchUtil.hightLight(luceneQuery, data, "content","subject","subjectShort","synopsis","author","dept");
		    rs.setList(la);
		} catch (EmptyQueryException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
		}
	    
		if (rs!=null) {
			/*for (Object art:rs.getList()) {
		    	Article a=(Article) art;
		    	System.out.println("a.getSubject():"+a.getSubject());
		    }*/
		}else {
			rs=new Rs();
			rs.setList(new ArrayList<SearchTotalModel>());
		}
	    
		
	    
		return rs;
	}
	

}
