package eu.dnetlib.enabling.is.registry;

import java.io.IOException;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

/**
 * Resolves resource kinds (pending and normal from the application profile xml file).
 * 
 * @author marko
 * 
 */
public class ApplicationProfileResourceKindResolver implements ResourceKindResolver {

	/**
	 * information space application profile. Contains, among others, mappings for the.. TODO: move to a DAO.
	 * 
	 */
	private Document appProfile;

	public ApplicationProfileResourceKindResolver() {
		try {
			appProfile = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(
					getClass().getResourceAsStream("DRIVERInformationSpaceApplicationProfile.xml"));
		} catch (SAXException e) {
			throw new IllegalStateException("cannot parse information space application profile", e);
		} catch (IOException e) {
			throw new IllegalStateException("cannot parse information space application profile", e);
		} catch (ParserConfigurationException e) {
			throw new IllegalStateException("cannot parse information space application profile", e);
		}
	}

	/**
	 * get the default resource kind associated with a given resource type.
	 * 
	 * @param resourceType
	 *            resource type
	 * @return resourceType
	 * @throws XPathExpressionException
	 *             happens?
	 */
	@Override
	public String getNormalKindForType(final String resourceType) throws XPathExpressionException {
		final XPath xpath = XPathFactory.newInstance().newXPath();
		final String res = xpath.evaluate("//RESOURCE_TYPE[text() = '" + resourceType + "']/../../RESOURCE_KIND", appProfile);
		if (res.isEmpty())
			return null;
		return res;
	}

	/**
	 * find the associated pending typology for a given resource type.
	 * 
	 * @param resourceType
	 *            resource type
	 * @return pending resource kind
	 * @throws XPathExpressionException
	 *             shouldn't happen
	 */
	@Override
	public String getPendingKindForType(final String resourceType) throws XPathExpressionException {
		final XPath xpath = XPathFactory.newInstance().newXPath();
		final String res = xpath.evaluate("//RESOURCE_TYPE[text() = '" + resourceType + "']/../../PENDING_TYPOLOGY", appProfile);
		if (res.isEmpty())
			throw new NoSuchPendingCategoryException("no pending category for " + resourceType);
		return res;
	}

}
