package uk.org.adamretter.webexample.view.bean;

import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import uk.org.adamretter.webexample.ServiceLocator;
import uk.org.adamretter.webexample.service.ConferenceService;

public class ServiceLocatorBean implements ServiceLocator {	
    
    public ServiceLocatorBean() {
    }

    @Override
    public ConferenceService getConferenceService() {
        return lookupService(ConferenceService.class);
    }

    /**
     * Lookup service based on service bean name.
     *
     * @param serviceClass the service to lookup
     * @return the service
     */
    public <T> T lookupService(Class<T> serviceClass) {
        ServletContext context = (ServletContext)FacesContext.getCurrentInstance().getExternalContext().getContext();
        WebApplicationContext appContext = WebApplicationContextUtils.getRequiredWebApplicationContext(context);

        return appContext.getBean(serviceClass);
    }
}