package eu.dnetlib.index.utils;

import java.io.IOException;
import javax.xml.transform.*;

import eu.dnetlib.rmi.provision.IndexServiceException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.DocumentResult;
import org.dom4j.io.DocumentSource;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.core.io.Resource;

public class IndexSchemaFactory {

	private static final Log log = LogFactory.getLog(IndexSchemaFactory.class); // NOPMD by marko on 11/24/08 5:02 PM

	private final static String TEXT_FIELD_TYPE = "textFieldType";

	private Resource schemaTemplate;

	private String textFieldType;

	/**
	 * Transformer used to get the index schema.
	 */
	private Transformer transformer;

	public void init() throws TransformerConfigurationException, TransformerFactoryConfigurationError, DocumentException, IOException {

		transformer = TransformerFactory.newInstance().newTransformer(new DocumentSource(new SAXReader().read(getSchemaTemplate().getInputStream())));
		transformer.setParameter(TEXT_FIELD_TYPE, getTextFieldType());
	}

	/**
	 * @return the application of the schemaXslt transformation to the docIn document
	 * @throws IndexServiceException
	 */
	public String getSchema(final Document fields) throws IndexServiceException {

		log.debug("default field type: " + getTextFieldType());
		log.debug("building schema from fields: \n" + fields.asXML() + "\n");

		final DocumentResult result = new DocumentResult();
		try {
			transformer.transform(new DocumentSource(fields), result);
			String xml = result.getDocument().asXML();

			log.debug("new index schema:\n" + xml);

			return xml;
		} catch (TransformerException e) {
			throw new IndexServiceException(e);
		}
	}

	public Resource getSchemaTemplate() {
		return schemaTemplate;
	}

	@Required
	public void setSchemaTemplate(final Resource schemaTemplate) {
		this.schemaTemplate = schemaTemplate;
	}

	public String getTextFieldType() {
		return textFieldType;
	}

	@Required
	public void setTextFieldType(final String textFieldType) {
		this.textFieldType = textFieldType;
	}

}
