package eu.dnetlib.functionality.index.solr;

import java.io.IOException;

import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.schema.IndexSchema;

import eu.dnetlib.functionality.index.cql.CqlValueTransformerMap;
import eu.dnetlib.functionality.index.solr.cql.SolrTypeBasedCqlValueTransformerMapFactory;

/**
 * Index bean class.
 * 
 * @author claudio
 *
 */
public class SolrIndex {
	
	/**
	 * {@inheritDoc}
	 *
	 * @see eu.dnetlib.functionality.index.solr.LocalIndexServer
	 */
	private transient LocalIndexServer server;
	
	/**
	 * Index Data Structure Id.
	 */
	private transient String dsId;
	
	/**
	 * {@inheritDoc}
	 *
	 * @see org.apache.solr.schema.IndexSchema
	 */
	private transient IndexSchema indexSchema;
	
	/**
	 * {@inheritDoc}
	 *
	 * @see 	eu.dnetlib.functionality.index.solr.cql.SolrTypeBasedCqlValueTransformerMapFactory
	 */
	private transient SolrTypeBasedCqlValueTransformerMapFactory tMapFactory;

	/**
	 * Constructor for SolrIndex
	 * @param server
	 * 			the LocalIndexServer
	 * @param dsId
	 * 			Index Data Structure Id
	 * @param tMapFactory
	 * 			the transformation map factory.
	 */
	public SolrIndex(
			final LocalIndexServer server, 
			final String dsId,
			final SolrTypeBasedCqlValueTransformerMapFactory tMapFactory) {
		super();
		this.server = server;
		this.indexSchema = server.getSchema();
		this.dsId = dsId;
		this.tMapFactory = tMapFactory;
	}
	
	/**
	 * Alternative constructor.
	 * 
	 * @param server
	 * 			the LocalIndexServer
	 * @param tMapFactory
	 * 			the transformation map factory.
	 */
	public SolrIndex(final LocalIndexServer server, final SolrTypeBasedCqlValueTransformerMapFactory tMapFactory) {
		this(server, null, tMapFactory);
	}

	public CqlValueTransformerMap getValueTransformerMap() {
		return tMapFactory.getIt(indexSchema);
	}
	
	/**
	 * Adds a document to the index.
	 * @param doc
	 * 			input document
	 * @return
	 * 			org.apache.solr.client.solrj.response.UpdateResponse
	 * @throws SolrServerException
	 * 				could happen
	 * @throws IOException
	 * 				could happen
	 */
	public UpdateResponse add(final SolrInputDocument doc) 
		throws SolrServerException, IOException {

		return getServer().add(doc);
	}
	
	public SolrServer getServer() {
		return server.getServer();
	}

	public String getDsId() {
		return dsId;
	}

	public IndexSchema getIndexSchema() {
		return indexSchema;
	}
	
}
