package eu.dnetlib.index.solr.model;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import eu.dnetlib.clients.index.model.Any.ValueType;
import eu.dnetlib.clients.index.model.document.AbstractIndexDocument;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.SolrInputField;

// TODO: Auto-generated Javadoc

/**
 * The Class SolrIndexDocument an implementation of the index document for SOLR.
 */
public class SolrIndexDocument extends AbstractIndexDocument {

	/**
	 * Instantiates a new solr index document.
	 *
	 * @param schema the schema
	 * @param dsId   the ds id
	 */
	public SolrIndexDocument(final Map<String, ValueType> schema, final String dsId) {
		super(schema, dsId);
	}

	/**
	 * Instantiates a new solr index document.
	 *
	 * @param schema       the schema
	 * @param dsId         the ds id
	 * @param solrDocument the solr document
	 */
	public SolrIndexDocument(final Map<String, ValueType> schema, final String dsId, final SolrInputDocument solrDocument) {
		super(schema, dsId);
		addFields(solrDocument);
	}

	/**
	 * Adds the fields.
	 *
	 * @param solrDocument the solr document
	 */
	private void addFields(final SolrInputDocument solrDocument) {
		for (String name : solrDocument.getFieldNames()) {
			Collection<Object> fieldValues = solrDocument.getFieldValues(name);
			if (fieldValues.size() > 1)
				addField(name, fieldValues);
			else if (fieldValues.size() == 1)
				addField(name, fieldValues.iterator().next());
		}
	}

	/**
	 * Sets the content.
	 *
	 * @param solrDocument the new content
	 */
	public void setContent(final SolrInputDocument solrDocument) {
		addFields(solrDocument);
	}

	/**
	 * Gets the solr document.
	 *
	 * @return the solr document
	 */
	public SolrInputDocument getSolrDocument() {

		Map<String, SolrInputField> data = new HashMap<String, SolrInputField>();
		for (String key : fields.keySet()) {
			SolrInputField solrField = new SolrInputField(key);
			for (Object o : fields.get(key)) {
				solrField.addValue(o, 1.0f);
			}
			data.put(key, solrField);
		}
		return new SolrInputDocument(data);
	}
}
