package fr.cnam.joueur;

import java.util.*;
import java.rmi.*;
import java.rmi.server.*;
import java.rmi.registry.*;
import java.util.*;
import java.lang.reflect.*;

public class DynamicCreationAgent implements InvocationHandler
{
  private CreationAgent creationAgent;

  public DynamicCreationAgent() throws RemoteException
  {
    this.creationAgent = new CreationAgent();
  }

  public Object invoke(Object proxy,
                       Method m,
                       Object[] args) throws Throwable
    {
      if (m.getName().equals("creerAgent"))
        {
          String nomClasseAgent = (String)args[0];
          int    couleur        = (Integer)args[1];

          AgentInt agent = null;
          try{
            Class<?> classe = 
              Class.forName(nomClasseAgent,true, 
                            ClassLoader.getSystemClassLoader());
            Class[] parameter = new Class[3];
            parameter[0] = int.class;
            parameter[1] = FactoryAgentInt.class;
            parameter[2] = int.class;
            Constructor constr = classe.getConstructor(parameter);
            agent = (Agent)(constr.newInstance(couleur,
                                               FactoryAgent.getInstance(),
                                               FactoryAgent.getInstance().getPortRMI()));

            // Injection de dependance entre CreationAgent et la classe d'agent
            //
            creationAgent.setAgent(agent);
          }catch(Exception ex){
            System.out.println("Impossible de creer un agent dynamique de :"+nomClasseAgent);
            System.out.println("Creation d'un agent par defaut");
            try{
              m.invoke(creationAgent, args);
            }catch(Exception ex2){ex2.printStackTrace();}
          }
          return null; //void
        }
      else
        {
          return m.invoke(this.creationAgent, args);
        }
    }
}
