package eu.dnetlib.enabling.soap;

import java.util.Map;

import javax.xml.namespace.QName;
import javax.xml.ws.wsaddressing.W3CEndpointReference;

import org.springframework.beans.factory.annotation.Required;

import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpService;
import eu.dnetlib.enabling.locators.UniqueServiceLocator;
import eu.dnetlib.enabling.tools.OpaqueResource;
import eu.dnetlib.enabling.tools.StringOpaqueResource;
import eu.dnetlib.soap.AbstractEndpointReferenceBuilder;
import eu.dnetlib.soap.EndpointReferenceBuilder;

/**
 * Builds an epr given an ID to a datastructure.
 * 
 * @author marko
 * 
 */
public class DataStructureLookupEndpointReferenceBuilder extends AbstractEndpointReferenceBuilder<String> implements EndpointReferenceBuilder<String> {

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

	/**
	 * underlying ds epr builder.
	 */
	private DataStructureProfileEndpointReferenceBuilder dsEprBuilder;

	/**
	 * {@inheritDoc}
	 * 
	 * @see eu.dnetlib.soap.EndpointReferenceBuilder#getAddress(java.lang.Object)
	 */
	@Override
	public String getAddress(final String pid) {
		return dsEprBuilder.getAddress(getProfile(pid));
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see eu.dnetlib.soap.EndpointReferenceBuilder#getEndpointReference(java.lang.Object, java.lang.String, java.util.Map)
	 */
	@Override
	public W3CEndpointReference getEndpointReference(final String pid, final String referenceParam, final Map<QName, Object> attrs) {
		return dsEprBuilder.getEndpointReference(getProfile(pid), attrs);
	}

	/**
	 * obtain the ds profile
	 * 
	 * @param pid
	 *            datastructure profile
	 * @return resource
	 */
	private OpaqueResource getProfile(final String pid) {
		try {
			return new StringOpaqueResource(serviceLocator.getService(ISLookUpService.class).getResourceProfile(pid));
		} catch (Exception e) { // TODO: remove this hack (conversion to unchecked exception)
			throw new IllegalStateException(e);
		}
	}

	public DataStructureProfileEndpointReferenceBuilder getDsEprBuilder() {
		return dsEprBuilder;
	}

	@Required
	public void setDsEprBuilder(final DataStructureProfileEndpointReferenceBuilder dsEprBuilder) {
		this.dsEprBuilder = dsEprBuilder;
	}

	public UniqueServiceLocator getServiceLocator() {
		return serviceLocator;
	}

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

}
