package eu.dnetlib.enabling.locators;

import java.util.HashMap;
import java.util.Map;

import javax.xml.ws.WebServiceFeature;
import javax.xml.ws.wsaddressing.W3CEndpointReference;

import eu.dnetlib.common.rmi.BaseService;
import eu.dnetlib.soap.cxf.StandaloneCxfEndpointReferenceBuilder;

/**
 * This bean packages the minimum information for describing a service running instance.
 */
public class ServiceRunningInstance {

	private String serviceId;
	private String url;
	private BaseService localService;
	private int usedDiskSpace = 0;
	private int handledDatastructures = 0;
	private Map<String, String> serviceProperties = new HashMap<String, String>();

	public ServiceRunningInstance() {}

	public ServiceRunningInstance(final String serviceId, final String url) {
		this.serviceId = serviceId;
		this.url = url;
	}

	public ServiceRunningInstance(final String serviceId, final String url, final BaseService localService, final int usedDiskSpace,
			final int handledDatastructures, final Map<String, String> serviceProperties) {
		this.serviceId = serviceId;
		this.url = url;
		this.localService = localService;
		this.usedDiskSpace = usedDiskSpace;
		this.handledDatastructures = handledDatastructures;
		this.serviceProperties = serviceProperties;
	}

	public boolean isLocal() {
		return localService != null;
	}

	synchronized public <T extends BaseService> T obtainClient(final Class<T> clazz, final StandaloneCxfEndpointReferenceBuilder eprBuilder) {
		if (isLocal() && clazz.isInstance(localService)) {
			return clazz.cast(localService);
		} else {
			final W3CEndpointReference epr = eprBuilder.getEndpointReference(url, null, null, url + "?wsdl", null, null);
			return epr.getPort(clazz, new WebServiceFeature[] {});
		}
	}

	public String getServiceId() {
		return serviceId;
	}

	public void setServiceId(final String serviceId) {
		this.serviceId = serviceId;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(final String url) {
		this.url = url;
	}

	public BaseService getLocalService() {
		return localService;
	}

	public void setLocalService(final BaseService localService) {
		this.localService = localService;
	}

	public Map<String, String> getServiceProperties() {
		return serviceProperties;
	}

	public void setServiceProperties(final Map<String, String> serviceProperties) {
		this.serviceProperties = serviceProperties;
	}

	public int getUsedDiskSpace() {
		return usedDiskSpace;
	}

	public void setUsedDiskSpace(final int usedDiskSpace) {
		this.usedDiskSpace = usedDiskSpace;
	}

	public int getHandledDatastructures() {
		return handledDatastructures;
	}

	public void setHandledDatastructures(final int handledDatastructures) {
		this.handledDatastructures = handledDatastructures;
	}

}
