package es.ejie.frmk.negocio.adaptadorinvocacion.dynamic;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import javax.naming.NamingException;

import es.ejie.frmk.infraestructura.logs.base.Q70LogInterno;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2003</p>
 * <p>Company: </p>
 * @author not attributable
 * @version 1.0
 */

public class Q70ServiceFactory
{

	private final static String LOCAL_PREFIX = "local:ejb/";
	private Q70ServiceFactory()
	{}
	public static Object getService(String jndiName)
	{
		return getService(jndiName, false);
	}
	public static Object getService(String jndiName, boolean isRemote)
	{
		Object home = null;
		//Obtener el home remoto
		if (isRemote)
		{
			try
			{
				home = Q70EjbFactory.getEjbHome(jndiName);
			}
			catch (NamingException e1)
			{
				e1.printStackTrace();
			}
		}
		//obtener el home local
		else
		{
			try
			{
				home = Q70EjbFactory.getEjbHome(LOCAL_PREFIX + "jndiName");
			}
			catch (NamingException ne)
			{
				ne.printStackTrace();
			}
		}
		Object prueba = null;

		try
		{
			//invocar al método create dinámicamente.
			Method m = home.getClass().getMethod("create", new Class[] {});
			prueba = m.invoke(home, new Object[] {});

			//imprimir las interfaces del objeto resultante.
			Class[] interfaces = prueba.getClass().getInterfaces();
			for (int i = 0; i < interfaces.length; i++)
			{
				if(Q70LogInterno.isEnabled())
					Q70LogInterno.log("intefaz: " + interfaces[i].getName());
			}
		}
		catch (SecurityException e)
		{
			e.printStackTrace();
		}
		catch (IllegalArgumentException e)
		{
			e.printStackTrace();
		}
		catch (NoSuchMethodException e)
		{
			e.printStackTrace();
		}
		catch (IllegalAccessException e)
		{
			e.printStackTrace();
		}
		catch (InvocationTargetException e)
		{
			e.printStackTrace();
		}

		//crear y devolver el proxy
		Object ret=null;
		try
		{
		
			ClassLoader cl = prueba.getClass().getClassLoader();
			ret = Proxy.newProxyInstance(cl, prueba.getClass().getInterfaces(), new Q70ServiceHandler(prueba));
		}
		catch(Throwable e)
		{
			e.printStackTrace();		
		}
		return ret;
	}

}