package eu.dnetlib.enabling.tools;

import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import eu.dnetlib.enabling.tools.registration.ServiceRegistrationManager;

/**
 * This service locator returns always one service instance.
 * 
 * Usually declared as a spring bean an injected in service when a static configuration is needed.
 * 
 * @author marko
 * 
 * @param <T>
 *            the type of the service
 */
@Deprecated
public class StaticServiceLocator<T> extends AbstractServiceLocator<T> implements ApplicationContextAware {

	/**
	 * static service reference.
	 */
	private T service;

	private ApplicationContext applicationContext;
	
	/**
	 * default constructor. initialize with setter.
	 */
	public StaticServiceLocator() {
		// no operation
	}
	
	/**
	 * construct a static service locator pointing at a given service.
	 * 
	 * @param service
	 *            service
	 */
	public StaticServiceLocator(final T service) {
		this.service = service;
	}

	/** 
	 * The usual usage pattern of service locators is to call chain a direct call
	 * on the result of this method. In order to avoid nullpointer exception, this method throws an exception
	 * with a better explanation, in case the service is null. 
	 * 
	 * TODO: consider using checked exceptions.
	 * 
	 * {@inheritDoc}
	 * @see eu.dnetlib.enabling.tools.ServiceLocator#getService()
	 */
	@Override
	public T getService() {
		if (service == null) {
			throw new IllegalStateException("cannot find service, check configuration");
		}
		return service;
	}

	@Override
	public String getServiceId() {
		final Map<String, ServiceRegistrationManager> beans = applicationContext.getBeansOfType(ServiceRegistrationManager.class);
		
		if (beans != null) {
			for (ServiceRegistrationManager r : beans.values()) {
				if (r.getService() == getService()) {
					return r.getServiceProfile().getResourceId();
				}
			}
		}
		throw new IllegalStateException("cannot find service, check configuration");
	}
	
	@Required
	public void setService(final T service) {
		this.service = service;
	}

	@Override
	public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;	
	}

}
