package eu.dnetlib.functionality.index.query;

import java.util.Arrays;

import eu.dnetlib.functionality.cql.lucene.TranslatedQuery;
import eu.dnetlib.functionality.index.client.IndexClient;
import eu.dnetlib.functionality.index.query.Pruner.Result;
import eu.dnetlib.functionality.index.solr.utils.HighlightUtils;
import eu.dnetlib.functionality.index.utils.IndexFieldUtility;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * A factory for creating SolrIndexQuery objects.
 */
public class SolrIndexQueryFactory extends IndexQueryFactory {

	/**
	 * logger.
	 */
	private static final Log log = LogFactory.getLog(SolrIndexQueryFactory.class);

	/** The Property name SERVICE_HIGHLIGHT_ENABLE. */
	private static final String SERVICE_HIGHLIGHT_ENABLE = "service.index.solr.highlight.enable";

	/*
	 * (non-Javadoc)
	 * 
	 * @see eu.dnetlib.functionality.index.query.IndexQueryFactory#newInstance(eu.dnetlib.functionality.index.cql.TranslatedQuery,
	 * eu.dnetlib.functionality.index.query.Pruner.Result, eu.dnetlib.functionality.index.query.QueryLanguage)
	 */
	@Override
	protected IndexQuery newInstance(final TranslatedQuery cql, final Result res, final QueryLanguage lang) {

		switch (lang) {
		case CQL:
			return new SolrIndexQuery(cql, res.getOptionMap());
		case SOLR:
			return new SolrIndexQuery(res.getNode().toCQL(), res.getOptionMap());
		default:
			throw new IllegalArgumentException("invalid query language: " + lang);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see eu.dnetlib.functionality.index.query.IndexQueryFactory#setQueryOptions(eu.dnetlib.functionality.index.query.IndexQuery,
	 * eu.dnetlib.functionality.index.IndexServerDAO)
	 */
	@Override
	protected IndexQuery setQueryOptions(final IndexQuery indexQuery, final IndexClient client) {

		final SolrIndexQuery solrQuery = (SolrIndexQuery) indexQuery;

		boolean isHighlightEnabled = Boolean.parseBoolean(client.getServiceProperties().get(SERVICE_HIGHLIGHT_ENABLE));
		if (solrQuery.getHighlight() & isHighlightEnabled) {
			solrQuery.setHighlightFragsize(0).setHighlightSnippets(1).setHighlightSimplePre(HighlightUtils.DEFAULT_HL_PRE)
					.setHighlightSimplePost(HighlightUtils.DEFAULT_HL_POST).addHighlightField(IndexFieldUtility.RESULT)
					.addField(IndexFieldUtility.INDEX_RECORD_ID);
		}

		solrQuery.addField(IndexFieldUtility.RESULT);
		if (solrQuery.getFacetFields() != null) {
			log.debug("getFacetFields() " + Arrays.asList(solrQuery.getFacetFields()));
			solrQuery.setFacetMinCount(1);
		}

		return solrQuery;
	}

}
