/**
 * @(#)$Id: MockServerInvocationHandler.java,v 1.11.2.2 2004/01/11 07:11:04 telrod Exp $
 *
 * This code is PROPRIETARY AND CONFIDENTIAL to Vocalocity, Inc.
 * -- DO NOT RE-DISTRIBUTE THIS SOURCE CODE WITHOUT EXPRESS PERMISSION. --
 *
 * This source code is Copyright (c) 2003 by Vocalocity, Inc.
 * All Rights Reserved.
 *
 * The source code for this program is not published or
 * otherwise divested of its trade secrets, irrespective
 * of what has been deposited with the US Copyright Office.
 *
 */
package org.jboss.remoting.transport.mock;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.management.MBeanServer;

import org.jboss.logging.Logger;
import org.jboss.remoting.Client;
import org.jboss.remoting.invocation.InternalInvocation;
import org.jboss.remoting.InvocationRequest;
import org.jboss.remoting.InvokerCallbackHandler;
import org.jboss.remoting.InvokerLocator;
import org.jboss.remoting.ServerInvocationHandler;
import org.jboss.remoting.ServerInvoker;
import org.jboss.remoting.invocation.NameBasedInvocation;
import test.ComplexReturn;
import test.classloading.server.Bar;

/**
 * MockServerInvocationHandler
 *
 * @author <a href="mailto:jhaynie@vocalocity.net">Jeff Haynie</a>
 * @author <a href="mailto:telrod@e2technologies.net">Tom Elrod</a>
 * @version $Revision: 1.11.2.2 $
 */
public class MockServerInvocationHandler implements ServerInvocationHandler
{
   private ServerInvoker invoker;
   private List listeners = new ArrayList();
   private Map clientListeners = new HashMap();

   private static final Logger log = Logger.getLogger(MockServerInvocationHandler.class);


   /**
    * set the invoker that owns this handler
    *
    * @param invoker
    */
   public void setInvoker(ServerInvoker invoker)
   {
      this.invoker = invoker;
   }

    /**
     * called to destroy the handler
     */
    public void destroy() {

    }

   /**
    * set the mbean server that the handler can reference
    *
    * @param server
    */
   public void setMBeanServer(MBeanServer server)
   {
   }

   public Object invoke(InvocationRequest invocation)
      throws Throwable
   {
      Object param = invocation.getParameter();
      String methodName = "";
      Object[] params = null;
      String[] sig = null;

      if (param instanceof NameBasedInvocation)
      {
          NameBasedInvocation nbi = (NameBasedInvocation)param;
          methodName = nbi.getMethodName();
          params = nbi.getParameters();
          sig = nbi.getSignature();
      }
      else if(param instanceof InternalInvocation)
      {
          InternalInvocation ii = (InternalInvocation)param;
          methodName = ii.getMethodName();
          params = ii.getParameters();
      }
      else
      {
          throw new Exception("Unknown invocation payload (parameter).  " +
                              "Should either be instance of NameBasedInvocation " +
                              "or InternalInvocation");
      }

      String sessionId = invocation.getSessionId();
      String subsystem = invocation.getSubsystem();

      log.debug("invoke() called with method: " + methodName +
                "\tsessionId: " + sessionId + "\tsubsystem:" + subsystem);
      if(methodName.equals("server_fail_class"))
      {
         // add the Bar class to the path
         invoker.addClass(new org.jboss.remoting.loading.ClassBytes("Bar", invoker.getClassBytes("Bar")));
         // load a class
         Class cl = invoker.loadClass("[LBar;");
         invocation.getReturnPayload().put("foo", "bar");
         invocation.getReturnPayload().put("hello", cl);
         // return an array of the dynamic Bar class to test both
         // dynamic client classloading as well as array creation
         return cl.getComponentType().newInstance();
      }
      else if(methodName.equals("printFoo"))
      {
         Object clientObj = params[0];
         // should call on Foo (which would be param passed)
         clientObj.toString();
         Bar ret = new Bar();
         return ret;
      }
      //deprecated since specific to JMX (old way of handling callbacks)
      else if(methodName.equals("addNotificationListener"))
      {
         // will assume each session id is unique for the invoker client
         handleAddNotificationListener(invocation.getLocator(), subsystem, sessionId);
         return null;
      }
      //deprecated since specific to JMX (old way of handling callbacks)
      else if(methodName.equals("removeNotificationListener"))
      {
         handleRemoveNotificationListener(sessionId);
         return null;
      }
      else if(methodName.equals("testComplexReturn"))
      {
          //Need to send back complex object containing array of complext objects.
          ComplexReturn ret = new ComplexReturn();
          return ret;
      }
      else if(methodName.equals("test"))
      {
         // will cause a callback on all the listeners
         log.debug("test called on server invocation handler, so should do callback.");
         //DEBUG: Just passing back garbage for now -TME
         CallbackDispatcher callbackDispatcher = new CallbackDispatcher(
            invocation.getSessionId(),
            invocation.getSubsystem(),
            new NameBasedInvocation("handleCallback",
                                    params,
                                    sig));
         Thread callbackThread = new Thread(callbackDispatcher);
         callbackThread.start();
      }
      else if(methodName.equals("addClientListener"))
      {
         Object obj = params[0];
         InvokerCallbackHandler clientHandler = (InvokerCallbackHandler) obj;

         clientListeners.put(invocation.getSessionId(), clientHandler);
      }
      else if(methodName.equals("removeClientListener"))
      {
         Object obj = params[0];
         InvokerCallbackHandler clientHandler = (InvokerCallbackHandler) obj;

         clientListeners.remove(invocation.getSessionId());
      }
      else if(methodName.equals("handleCallback"))
      {
         // got a callback from remote server
         InvokerCallbackHandler clientHandler = (InvokerCallbackHandler) clientListeners.get(sessionId);
         clientHandler.handleCallback(invocation);
      }
      Object ret = null;
      if (params != null)
      {
         ret = params[0];
         log.info("Found a parameter to return " + ret);
      } // end of if ()
      else
      {
         log.info("returning null");
      } // end of else

      return ret;
   }

   /**
    * @deprecated
    * @param sessionId
    */
   private void handleRemoveNotificationListener(String sessionId)
   {
      listeners.remove(sessionId);
   }

   /**
    * @deprecated
    * @param clientLocator
    * @param subsystem
    * @param sessionId
    * @throws Exception
    */
   private void handleAddNotificationListener(InvokerLocator clientLocator,
                                              String subsystem,
                                              String sessionId) throws Exception
   {
      Client callBackClient = new Client(clientLocator, subsystem);
      callBackClient.connect();
      listeners.add(callBackClient);
   }

   public void addListener(InvokerCallbackHandler callbackHandler)
   {
      listeners.add(callbackHandler);
      log.debug("added listener " + callbackHandler);
   }

   public void removeListener(InvokerCallbackHandler callbackHandler)
   {
      listeners.remove(callbackHandler);
      log.debug("removed listener " + callbackHandler);
   }

   private class CallbackDispatcher implements Runnable
   {
      private String sessionId;
      private String subsystem;
      private Object param;

      public CallbackDispatcher(String sessionId, String subsystem, Object param)
      {
         this.sessionId = sessionId;
         this.subsystem = subsystem;
         this.param = param;
      }

      public void run()
      {
         Iterator itr = listeners.iterator();
         while(itr.hasNext())
         {
            try
            {
               //TODO: Currently throwing away real args, need to append id instead -TME
               InvokerCallbackHandler handler = (InvokerCallbackHandler)itr.next();
               InvocationRequest invocation = new InvocationRequest(
                  sessionId,
                  subsystem,
                  param,
                  /* BIG CHANGE -- I'm not sending the id here, it seems redundant (daje)
                     methodName,
                     new Object[]{handler.getId()},
                     new String[]{String.class.getName()},
                  */
                  null, //Map requestPayload
                  null, //Map returnPayload
                  null); //InvokerLocator client
               handler.handleCallback(invocation);
            }
            catch(Throwable e)
            {
               e.printStackTrace();
            }

         }
      }
   }
}
