package org.eclipse.stp.sc.common.runtime;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtension;
import org.eclipse.core.runtime.IExtensionRegistry;
import org.eclipse.core.runtime.Platform;
import org.eclipse.stp.common.logging.LoggingProxy;
import org.eclipse.stp.sc.common.CommonPlugin;

public class ExtRuntimeManager {
	private static final LoggingProxy LOG = LoggingProxy.getlogger(ExtRuntimeManager.class);
	
	private final static String EXT_POINT_ID = CommonPlugin.PLUGIN_ID + ".ExtRuntimeProcessor";
	private final static String EXT_ELEMENT_NAME = "processor";
	private final static String EXT_ELEMENT_ATTR_CLASS = "class";
	private final static String EXT_ELEMENT_ATTR_RUNTIMETYPE = "runtimeTypeID";
	
	private ExtRuntimeManager(){
		
	}
	
	private static ExtRuntimeManager instance;
	
	public synchronized static ExtRuntimeManager getInstance(){
		if(instance == null){
			instance = new ExtRuntimeManager();
		}
		return instance;
	}
	
	public IExtRuntimeProcessor getExtendedRuntimeProcessor(String runtimeTypeID){
		IExtRuntimeProcessor retValue = null;
		IExtensionRegistry reg = Platform.getExtensionRegistry();
        IExtension[] extensions = reg.getExtensionPoint(EXT_POINT_ID).getExtensions();
        if(extensions != null && extensions.length > 0){
        	for(IExtension ext : extensions){
        		IConfigurationElement[] elements = ext.getConfigurationElements();
        		if(elements != null && elements.length > 0){
        			for(IConfigurationElement element : elements){
        				if(element.getName().equals(EXT_ELEMENT_NAME)){
        					if(element.getAttribute(EXT_ELEMENT_ATTR_RUNTIMETYPE).equals(runtimeTypeID)){
        						try{
        							Object obj = element.createExecutableExtension(EXT_ELEMENT_ATTR_CLASS);
        							if(obj instanceof IExtRuntimeProcessor){
        								retValue = (IExtRuntimeProcessor)obj;
        								return retValue;
        							}
        						}catch(CoreException ex){
        							LOG.error("error while create extended runtime processor", ex);
        						}
        					}
        				}
        			}
        		}
        	}
        }
		return retValue;
	}
}
