/**
 * 
 */
package eu.dnetlib.data.information;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Properties;

import eu.dnetlib.data.mdstore.IMDStoreService;
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpDocumentNotFoundException;
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpException;

/**
 * @author jochen
 *
 */
public abstract class AbstractMDStoreResolver extends AbstractDataSinkSourceResolver{

	private static final String URI_AUTHORITY = "MDStoreDS";
	

	/**
	 * parses the descriptor string and extracts all the required parameters.
	 *
	 * @param descriptor descriptor string
	 * @return parsed descriptor component, specific to mdstores
	 */
	protected MDStoreParameters parseDescriptor(final String descriptor) {
		try {
			final URI uri = new URI(descriptor);

			if (!uri.getAuthority().equals(URI_AUTHORITY))
				throw new IllegalStateException("unexpected uri descriptor " + descriptor + ". This sink resolver is specific for " + URI_AUTHORITY);

			final String query = uri.getQuery();
			Properties parameters = new Properties();
			if (query != null){
				for(final String component : query.split("&")) {
					if(component.startsWith("type="))
						parameters.setProperty("type", component.split("=")[1]);
					else if (component.startsWith("from="))
						parameters.setProperty("from", component.split("=")[1]);
				}				
			}
			return new MDStoreParameters(uri.getPath().substring(1), parameters);

		} catch (final URISyntaxException e) {
			throw new IllegalStateException(e);
		}

	}
	
	protected IMDStoreService getMDStoreService(String aId) throws ISLookUpDocumentNotFoundException, ISLookUpException{
		final String xquery = "replace(//RESOURCE_PROFILE[.//RESOURCE_IDENTIFIER/@value='" + aId + "']//RESOURCE_URI/@value, '\\?wsdl$', '')";
		final String url = this.getLookupLocator().getService().getResourceProfileByQuery(xquery);
		return this.getServiceResolver().getService(IMDStoreService.class, this.getEprBuilder().getEndpointReference(url, null, null, url
				+ "?wsdl", null, null));
	}

}
