package eu.dnetlib.enabling.tools;

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

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

/**
 * Locates a registered HNM running on a given url.
 *
 * @author marko
 *
 */
@Deprecated
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

	/**
	 * service locator.
	 */
	UniqueServiceLocator serviceLocator;

	/**
	 * {@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 serviceLocator.getService(ISLookUpService.class).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 UniqueServiceLocator getServiceLocator() {
		return serviceLocator;
	}

	@Required
	public void setServiceLocator(UniqueServiceLocator serviceLocator) {
		this.serviceLocator = serviceLocator;
	}

}
