/**
 *  Protocol port factory (Singleton)
 *  
 *  @author     ETSI / STF424
 *  @version    $URL$
 *              $Id$
 *
 */
package org.etsi.ttcn.extfunc.core;

import java.lang.reflect.Constructor;
import java.util.Map;
import java.util.TreeMap;

import org.etsi.common.plugins.IXfPlugin;
import org.etsi.common.plugins.PluginLoader;

/**
 *  Protocol port factory (Singleton)
 */
public class XfFactory {
	
	private static boolean initialized = false;

    /**
     * Unique instance of the factory
     */
    private static XfFactory instance = new XfFactory();
        
    /**
     * List of the registered protocol port types 
     */
    protected Map<String, Class<? extends ExternalFunction>> xfs = new TreeMap<String, Class<? extends ExternalFunction>>();
    
    /**
     * Private constructor (Singleton pattern)
     */
    private XfFactory() {
        // empty
    }

    /**
     * Gets the unique factory instance
     * @return ProtocolPortFactory instance
     */
    public static XfFactory getInstance() {
    	
    	instance.initialize();
        return instance;
    }
    
    public void initialize() {
        
        if(!initialized) {
            initialized = true; 
            
            PluginLoader pl = new PluginLoader(IXfPlugin.class, "org.etsi.ttcn.extfunc");
            pl.load(new String[] {"./lib", "./plugins", "./build"});
        }
    }
    
    public ExternalFunction getXf(String xfName) {
    	// FIXME: temporary
    	Class<? extends ExternalFunction> cls = xfs.entrySet().iterator().next().getValue();;
        Class<?>[] ctorParams1 = {};
    	 
    	try {
            Constructor<? extends ExternalFunction> ctor = cls.getConstructor(ctorParams1);
            return ctor.newInstance();
        } 
         catch (Exception ex) {
             ex.printStackTrace();
         }
    	
		return null;
    }
    
    public void registerXf(String xfName, Class<? extends ExternalFunction> portClass) {
    	System.err.println("Registering XF: " + xfName);
    	xfs.put(xfName, portClass);
    }
}
 