package eu.dnetlib.functionality.index.solr;

import java.io.IOException;
import java.io.StringReader;
import java.text.ParseException;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrInputDocument;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.util.StringUtils;
import org.xml.sax.SAXException;
import org.z3950.zing.cql.CQLParseException;

import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;

import eu.dnetlib.common.ws.dataprov.ResultsResponse;
import eu.dnetlib.enabling.resultset.client.IterableResultSetClient;
import eu.dnetlib.functionality.index.cql.CqlTranslator;
import eu.dnetlib.functionality.index.solr.SolrIndexServiceImpl.FeedMode;
import eu.dnetlib.functionality.index.solr.feed.FeedResult;
import eu.dnetlib.functionality.index.solr.feed.IndexDocument;
import eu.dnetlib.functionality.index.solr.feed.InputDocumentFactory;
import eu.dnetlib.functionality.index.solr.mapping.IndexDocumentMapper;
import eu.dnetlib.functionality.index.solr.mapping.IndexDocumentMapperFactory;
import eu.dnetlib.functionality.index.solr.query.IndexQuery;
import eu.dnetlib.functionality.index.solr.query.IndexQueryFactory;
import eu.dnetlib.functionality.index.solr.query.QueryLanguage;
import eu.dnetlib.functionality.index.solr.query.QueryResponseFactory;
import eu.dnetlib.functionality.index.solr.query.QueryResponseParser;
import eu.dnetlib.functionality.index.solr.utils.IndexMap;
import eu.dnetlib.functionality.index.solr.utils.MetadataReference;
import eu.dnetlib.functionality.index.solr.utils.ServiceTools;

/**
 * 
 * @author claudio
 *
 */
public class SolrIndexServer {
	
	/**
	 * logger
	 */
	private static final Log log = LogFactory.getLog(SolrIndexServer.class);
	
	/**
	 * query factory
	 */
	private IndexQueryFactory indexQueryFactory;
	
	/**
	 * document factory used for the feed process.
	 */
	private InputDocumentFactory documentFactory;
	
	private IndexDocumentMapperFactory documentMapperFactory;
	
	/**
	 * response factory. 
	 */
	private QueryResponseFactory queryResponseFactory;
	
	/**
	 * contains handled index data structures.
	 */
	private IndexMap indexMap;
	
	/**
	 * Query used to match all the records.
	 */
	private static String queryAll = "*";
	
	private ServiceTools serviceTools;
	
	private CqlTranslator translator;
	
	/**
	 * initializer
	 * 
	 * @throws SolrException could happen 
	 * @throws DocumentException 
	 * @throws Exception 
	 */
	public void init() throws Exception {
	
		log.info("Initializing SolrIndexServer, trying to resume existing indexes");
		final List<String> indexNames = indexMap.getExistingIndexNames();
		
		for (String indexName : indexNames ) {
			final MetadataReference mdRef = indexMap.getMetadataReference(indexName);
			final List<String> dsId = serviceTools.getIndexDsIdsList(mdRef);
			
			if (dsId != null) {
				indexMap.register(parseFields(serviceTools.getIndexFields(mdRef)), mdRef, dsId);
				log.info("loaded " + indexMap.getDsId(indexName).size() + " dataStructure references for index " + indexName);
			} else 
				log.warn("couldn't find any referenced dataStructure lo load for index: " + indexName);
		}
		log.info("resume report: " + indexNames.size() + " indexes resumed: " + indexNames.toString());
	}
	
	private Document parseFields(final String fields) throws DocumentException {
		return (new SAXReader()).read(new StringReader(fields));
	}
	
	/**
	 * creates an index
	 * 
	 * @param dsId
	 * @param mdRef
	 * @param fields
	 * @throws Exception
	 */
	public void create(
			final String dsId,
			final MetadataReference mdRef,
			final String fields) 
		throws Exception {
		
		log.info("registering DSId: " + dsId);
		indexMap.register(parseFields(fields), mdRef, Lists.newArrayList(dsId));
	}
	
	/**
	 * feeds the documents provided by the {@link IterableResultSetClient} to the index specified by the dsId
	 * 
	 * @param dsId
	 * @param version
	 * @param documentIterator
	 * @return
	 * @throws SolrServerException
	 * @throws IOException
	 * @throws CQLParseException 
	 * @throws ParseException 
	 * @throws SAXException 
	 * @throws ParserConfigurationException 
	 */
	public void feed(
			final String dsId, 
			final String version, 
			final FeedMode feedMode,
			final IterableResultSetClient documentIterator) 
		throws SolrServerException, IOException, CQLParseException, ParseException, ParserConfigurationException, SAXException {
		
		final FeedResult res = new FeedResult(System.currentTimeMillis());
		
		final SolrIndex index = indexMap.getIndexByDs(dsId);
		
		Iterable<IndexDocument> indexDocs = Iterables.transform(documentIterator, new Function<String, IndexDocument>() {
			@Override
			public IndexDocument apply(String doc) {
				return documentFactory.getInputDocument(index, version, doc);
			}
		});
		
		Iterable<IndexDocument> filteredDocs = filterByStatus(indexDocs, res);
		
		IndexDocumentMapper documentMapper = documentMapperFactory.newInstance(indexMap.getIndexName(dsId));
		
		Iterable<SolrInputDocument> inputDocs = Iterables.transform(filteredDocs, documentMapper);
		
		index.add(inputDocs);
		cleanMarkedDocuments(dsId);

		if (feedMode.equals(FeedMode.REFRESH))
			deleteByVersion(dsId, version);
			// otherwise, solr automatically overwrites records with the same objIdentifier: INCREMENTAL mode.

		commit(dsId);		
		res.setTimeElapsed(System.currentTimeMillis());
		log.info("FeedResult: " + res.toString());
	}	
	
	/**
	 * TODO feed documents w/o needing to retrieve the original document from the index: simply adding 
	 * 		the new field
	 * 
	 * @param dsId
	 * @param documentIterator
	 * @return
	 * @throws SolrServerException
	 * @throws IOException
	 * @throws CQLParseException 
	 */
	public FeedResult feedFulltext(final String dsId, final IterableResultSetClient documentIterator) 
		throws SolrServerException, IOException, CQLParseException {
		
		final FeedResult res = new FeedResult(System.currentTimeMillis());
		final SolrIndex index = indexMap.getIndexByDs(dsId);
		
		Iterable<IndexDocument> indexDocs = Iterables.transform(documentIterator, new Function<String, IndexDocument>() {
			@Override
			public IndexDocument apply(String fullTextMetadata) {
				try {
					return documentFactory.getFullTextDocument(index, fullTextMetadata);
				} catch (CQLParseException e) {
					throw new RuntimeException(e);
				}
			}
		});
		
		Iterable<IndexDocument> filteredDocs = filterByStatus(indexDocs, res);
		
		IndexDocumentMapper documentMapper = documentMapperFactory.newInstance(indexMap.getIndexName(dsId));
		Iterable<SolrInputDocument> inputDocs = Iterables.transform(filteredDocs, documentMapper );
		
		index.add(inputDocs);
		
		return res.setTimeElapsed(System.currentTimeMillis());
	}
	
	/**
	 * helper method, parses document's {@link IndexDocument.STATUS} to updates the FeedResult,
	 * if the STATUS is OK, feeds the document.
	 * 
	 * @param document
	 * 			document whose status must be parsed
	 * @param dsId
	 * 			index dataStructure Id needed to perform feeding
	 * @param res
	 * 			FeedResult to update
	 * @throws SolrServerException
	 * @throws IOException
	 */
	private Iterable<IndexDocument> filterByStatus(final Iterable<IndexDocument> documents, final FeedResult res) { 
		return Iterables.filter(documents, new Predicate<IndexDocument>() {
			@Override
			public boolean apply(IndexDocument doc) {
				switch (doc.getStatus()) {
					case OK:
						res.add();
						return true;
					case MARKED:
						res.mark();
						break;
					case ERROR:
						res.skip();
						break;					
					default:
						throw new IllegalStateException("unknow document status");
				}				
				return false;
			}
		});
	}
	
	/**
	 * method deletes all the documents that matches the specified cql 
	 * query from the index that handles the given dsId.
	 * 
	 * @param query
	 * @param dsId
	 * @return
	 * @throws CQLParseException
	 * @throws IOException
	 * @throws SolrServerException
	 */
	public long deleteByQuery(String query, final String dsId) 
		throws CQLParseException, IOException, SolrServerException {
		
		final String luceneQuery = translator.toLucene(query + " and " + IndexMap.DS_ID + " all " + dsId);
		final String indexName = indexMap.getIndexName(dsId);

		log.info("DELETE BY QUERY: " + luceneQuery + " on '" + indexName + "' physical index");
		
		return indexMap.getIndexByDs(dsId).getServer().deleteByQuery(luceneQuery).getElapsedTime();
	}
	
	/**
	 * method deletes all the documents of a specified dsId whose {@link IndexMap}.DS_VERSION 
	 * field is older than the specified mdFormatVersion. 
	 * 
	 * @param dsId
	 * @param mdFormatVersion
	 * @return
	 * 		the time elapsed to complete the operation.
	 * @throws SolrServerException
	 * @throws IOException
	 * @throws CQLParseException
	 * @throws ParseException
	 */
	public long deleteByVersion(final String dsId, final String mdFormatVersion) 
		throws SolrServerException, IOException, CQLParseException, ParseException {

		final String query = IndexMap.DS_VERSION + " < \"" + 
							 documentFactory.getParsedDateField(mdFormatVersion) + "\"";

		return deleteByQuery(query, dsId);
	}
	
	/**
	 * method delete documents where IndexMap.DELETE_DOCUMENT field is true 
	 * 
	 * @param dsId
	 * @return
	 * 		the time elapsed to complete the operation.
	 * @throws SolrServerException
	 * @throws IOException
	 * @throws CQLParseException
	 */
	public long cleanMarkedDocuments(final String dsId) 
		throws SolrServerException, IOException, CQLParseException {
	
		final String query = IndexMap.DELETE_DOCUMENT + " all true ";

		return deleteByQuery(query, dsId);
	}

	/**
	 * method queries the index to get the number of indexed documents
	 * of a specific dataStructure.
	 * 
	 * @param dsId
	 * @return
	 * 		the time elapsed to complete the operation.
	 * @throws CQLParseException
	 * @throws IOException
	 * @throws SolrServerException
	 * @throws DocumentException
	 */
	public ResultsResponse getNumberOfRecords(final String dsId) 
		throws CQLParseException, IOException, SolrServerException, DocumentException {

		final MetadataReference mdRef = indexMap.dsMetadataReference(dsId);
		final IndexQuery query = indexQueryFactory.getIndexQuery(QueryLanguage.CQL, queryAll, mdRef, dsId);
		final QueryResponseParser lookupRes = this.lookup(query, mdRef);
		 
		return newResultsResponse(lookupRes.getStatus(), lookupRes.getNumFound());
	}
	
	/**
	 * method performs a commit of the physical index delegated to handle the given dsId
	 * 
	 * @param dsId
	 * 			needed to retrieve the physical index.
	 * @return
	 * 			the time (ms) elapsed to complete the operation.
	 * @throws SolrServerException
	 * @throws IOException
	 * @throws SAXException 
	 * @throws ParserConfigurationException 
	 */
	public long commit(final String dsId) 
		throws SolrServerException, IOException, ParserConfigurationException, SAXException {

		return indexMap.getIndexByDs(dsId).getServer().commit().getElapsedTime();
	}

	/**
	 * method performs an optimization of the physical index delegated to handle the given dsId
	 * 
	 * @param dsId
	 * 			needed to retrieve the physical index.
	 * @return
	 * 			the time (ms) elapsed to complete the operation.
	 * @throws SolrServerException
	 * @throws IOException
	 * @throws SAXException 
	 * @throws ParserConfigurationException 
	 */
	public long optimize(final String dsId) 
		throws SolrServerException, IOException, ParserConfigurationException, SAXException {

		return indexMap.getIndexByDs(dsId).getServer().optimize().getElapsedTime();
	}
	
	/**
	 * method returns list of registered Store Data Structure identifiers.
	 * 
	 * @return a list of available indexes
	 */
	public String[] getIndexList() {

		return indexMap.getDsIdArray();
	}
	
	/**
	 * method returns list of registered Store Data Structure identifiers as comma-separated string.
	 * @return comma separated list index identifiers
	 */
	public String getIndexListCSV() {
	
		return StringUtils.arrayToCommaDelimitedString(getIndexList());
	}
	
	/**
	 * 
	 * @param idxId
	 * @param query
	 * @param fromPosition
	 * @param toPosition
	 * @return List<String> of matching records
	 * @throws SolrServerException
	 * @throws CQLParseException
	 * @throws IOException
	 * @throws DocumentException
	 */
	public QueryResponseParser lookup(final IndexQuery query, final MetadataReference mdRef) 
		throws SolrServerException, CQLParseException, IOException, DocumentException {

		final SolrServer server = indexMap.getIndexByMetadata(mdRef).getServer();
		return queryResponseFactory.getQueryResponseParser(server.query(query), mdRef);
	}
	
	/////////////////////////// helper
	
	private ResultsResponse newResultsResponse(final String status, final long total) {
		ResultsResponse res = new ResultsResponse();
		res.setStatus(status);
		res.setTotal((int)total);
		return res;
	}
	
	/////////////////////////// setters and getters
	
	public IndexQueryFactory getQueryFactory() {
		return indexQueryFactory;
	}
	
	@Required
	public void setQueryFactory(IndexQueryFactory indexQueryFactory) {
		this.indexQueryFactory = indexQueryFactory;
	}
	
	@Required
	public void setDocumentFactory(InputDocumentFactory documentFactory) {
		this.documentFactory = documentFactory;
	}
	
	@Required
	public void setQueryResponseFactory(QueryResponseFactory queryResponseFactory) {
		this.queryResponseFactory = queryResponseFactory; 
	}
	
	@Required
	public void setServiceTools(ServiceTools serviceTools) {
		this.serviceTools = serviceTools;
	}

	@Required
	public void setIndexMap(IndexMap indexMap) {
		this.indexMap = indexMap;
	}
	
	public IndexMap getIndexMap() {
		return indexMap;
	}

	@Required
	public void setTranslator(CqlTranslator translator) {
		this.translator = translator;
	}

	@Required
	public void setDocumentMapperFactory(IndexDocumentMapperFactory documentMapperFactory) {
		this.documentMapperFactory = documentMapperFactory;
	}

	public IndexDocumentMapperFactory getDocumentMapperFactory() {
		return documentMapperFactory;
	}

}
