package eu.dnetlib.functionality.index.solr.feed;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.xml.stream.XMLStreamException;

import org.apache.solr.common.SolrInputDocument;
import org.dom4j.DocumentException;

/**
 *
 * @author claudio
 *
 */
public abstract class InputDocumentFactory {

	public static final String INDEX_FIELD_PREFIX = "__";

	public static final String DS_VERSION = INDEX_FIELD_PREFIX + "dsversion";

	public static final String DS_ID = INDEX_FIELD_PREFIX + "dsid";

	public static final String RESULT = "result";

	public static final String INDEX_RESULT = INDEX_FIELD_PREFIX + RESULT;

	public static final String INDEX_RECORD_ID = INDEX_FIELD_PREFIX + "indexrecordidentifier";

	private static final String outFormat = new String("yyyy-MM-dd'T'hh:mm:ss'Z'");

	private final static List<String> dateFormats = Arrays.asList("yyyy-MM-dd'T'hh:mm:ss", "yyyy-MM-dd", "dd-MM-yyyy", "dd/MM/yyyy", "yyyy");

	public abstract SolrInputDocument parseDocument(final String version,
			final String inputDocument,
			final String dsId,
			final String resultName) throws XMLStreamException;

	public abstract SolrInputDocument parseDocument(final String version,
			final String inputDocument,
			final String dsId,
			final String resultName,
			final ResultTransformer resultTransformer) throws XMLStreamException;

	/**
	 * method return a solr-compatible string representation of a date
	 *
	 * @param date
	 * @return the parsed date
	 * @throws DocumentException
	 * @throws ParseException
	 */
	public static String getParsedDateField(final String date) {
		return new SimpleDateFormat(outFormat).format(tryParse(date));
	}

	public static Date tryParse(final String date) {
		for (String formatString : dateFormats) {
			try {
				return new SimpleDateFormat(formatString).parse(date);
			} catch (ParseException e) {}
		}
		throw new IllegalStateException("unable to parse date: " + date);
	}

	public String parseDate(final String date) {
		return getParsedDateField(date);
	}

}
