package eu.dnetlib.enabling.tools;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

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

/**
 * Locates a registered HNM running on a given url.
 *
 * @author marko
 *
 */
public class DynamicHNMLocator implements HNMLocator {

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

	/**
	 * is lookup locator.
	 */
	ServiceLocator<ISLookUpService> lookupLocator;

	/**
	 * {@inheritDoc}
	 *
	 * @see eu.dnetlib.enabling.tools.HNMLocator#getHNMForUrl(java.lang.String)
	 */
	@Override
	public String getHNMForUrl(final String url) {

		final String prefix = url.substring(0, url.indexOf('/', "http://".length()));
		final String query = "collection('')//RESOURCE_PROFILE[.//RESOURCE_TYPE/@value = 'HostingNodeManagerServiceResourceType' and starts-with(.//RESOURCE_URI/@value, '"
				+ prefix + "')]//RESOURCE_IDENTIFIER/@value/string()";

		try {
			return lookupLocator.getService().getResourceProfileByQuery(query);
		} catch (final ISLookUpDocumentNotFoundException e) {
			log.debug("doument not found for query: " + query);
			return null;
		} catch (final ISLookUpException e) {
			throw new IllegalStateException("cannot search hnm", e);
		}
	}

	public ServiceLocator<ISLookUpService> getLookupLocator() {
		return lookupLocator;
	}

	public void setLookupLocator(final ServiceLocator<ISLookUpService> lookupLocator) {
		this.lookupLocator = lookupLocator;
	}

}
