package eu.dnetlib.enabling.is.registry.schema;

import java.io.StringReader;

import javax.xml.XMLConstants;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Required;
import org.xml.sax.SAXException;

import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpException;
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpService;

/**
 * manages the resource schemas through the registry service.
 * 
 * @author marko
 * 
 */
public class ResourceSchemaDAOImpl implements ResourceSchemaDAO {

	private ISLookUpService isLookup;

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

	/**
	 * {@inheritDoc}
	 * 
	 * @see eu.dnetlib.enabling.is.registry.schema.ResourceSchemaDAO#getResourceSchema(java.lang.String)
	 */
	@Override
	public Schema getResourceSchema(final String resourceType) {
		try {
			final String schemaSource = isLookup.getResourceTypeSchema(resourceType);
			if (schemaSource == null || schemaSource.isEmpty()) {
				log.warn("cannot find resource type " + resourceType);
				return null;
			}
			return SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(new StreamSource(new StringReader(schemaSource)));
		} catch (ISLookUpException e) {
			log.warn("cannot find resource type" + resourceType, e);
			return null;
		} catch (SAXException e) {
			log.fatal("cannot parse resource type schema", e);
			return null;
		}
	}

	public ISLookUpService getIsLookup() {
		return isLookup;
	}

	@Required
	public void setIsLookup(final ISLookUpService isLookup) {
		this.isLookup = isLookup;
	}

}
