/**
 * @(#)$Id: TestServerInvocationHandler.java,v 1.3.2.1 2004/01/05 04:15:07 jhaynie 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 test.performance;

import EDU.oswego.cs.dl.util.concurrent.SynchronizedInt;
import org.jboss.logging.Logger;
import org.jboss.remoting.InvocationRequest;
import org.jboss.remoting.InvokerCallbackHandler;
import org.jboss.remoting.ServerInvocationHandler;
import org.jboss.remoting.ServerInvoker;
import org.jboss.remoting.invocation.RemoteInvocation;

import javax.management.MBeanServer;
import java.util.*;

import test.ShutdownListener;
import test.OnewayInvokerServerTest;

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

   int totalCount = 0;
   SynchronizedInt duplicateCount = new SynchronizedInt(0);
   SynchronizedInt receivedCount = new SynchronizedInt(0);

   private boolean[] counterArray = null;

   private final Object waitObj = new Object();
   private Timer processingCompleteTimer;
   private boolean processingWork = false;
   private ShutdownListener shutdownListener;
   private static final Logger log = Logger.getLogger(TestServerInvocationHandler.class);

   public TestServerInvocationHandler(ShutdownListener listener)
   {
      this.shutdownListener = listener;
   }

    /**
     * called to destroy the handler
     */
    public void destroy() {
       log.debug("destroy called");
    }


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

   /**
    * 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 RemoteInvocation)
      {
         RemoteInvocation rminvo = (RemoteInvocation) param;
         methodName = rminvo.getMethodName();
         params = rminvo.getParameters();
      }
      else
      {
         throw new Exception("Unknown invocation payload (" + param +").  " +
               "Should either be instance of RemoteInvocation.");
      }

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

      log.debug("invoke() called with method: " + methodName +
            "\tsessionId: " + sessionId + "\tsubsystem:" + subsystem);

      Object ret = null;
      if (methodName.equals("totalCallCount"))
      {
         String totalCountStr = (String) params[0];
         int totalCount = Integer.parseInt(totalCountStr);
         System.out.println("received totalCallCount call with total count of " + totalCount);
         createTotalCount(totalCount);
      }
      else if(methodName.equals("serverTotalCallCount"))
      {
         // Need to block thread till done getting all server calls processed so can return total
         int svrTotalCount = getServerTotalCount();
         System.out.println("Returning server total count: " + svrTotalCount);
         ret = String.valueOf(svrTotalCount);
      }
      else
      {
         if (params != null)
         {
            String paramCount = (String) params[0];
            int localClientInvokeCount = Integer.parseInt(paramCount);
            verifyClientInvokeCount(localClientInvokeCount);
            // just passing return, even though not needed to make sure gets thrown away before getting to client
            ret = paramCount;
         }
         else
         {
            log.error("no parameter passed");
         }
      }
      return ret;
   }

   private int getServerTotalCount()
   {
      synchronized (waitObj)
      {
         try
         {
            waitObj.wait(5 * 60 * 1000); // timeout if not notified
         }
         catch (InterruptedException e)
         {

         }
      }
      processingCompleteTimer.cancel();
      return receivedCount.get();
   }

   private void serverProcessingComplete()
   {
      System.out.println("server processing complete.");

      synchronized (waitObj)
      {
         waitObj.notify();
      }
      if(shutdownListener != null)
      {
         try
         {
            shutdownListener.shutdownTest();
         }
         catch (Exception e)
         {
            e.printStackTrace();
         }
      }
   }

   private synchronized void createTotalCount(int totalCount)
   {
      counterArray = new boolean[totalCount + 1];
      this.totalCount = totalCount;
      receivedCount.set(0);
      duplicateCount.set(0);
      startTimer();
   }

   private void startTimer()
   {
      processingCompleteTimer = new Timer();
      processingCompleteTimer.schedule(new CompetedTimerTask(), 1000, 1000);
   }

   private void verifyClientInvokeCount(int localClientInvokeCount)
   {
      processingWork = true;
      boolean duplicate = addToReceivedCount(localClientInvokeCount);
      if (duplicate)
      {
         duplicateCount.increment();
      }
      else
      {
         receivedCount.increment();
      }

      int currentDuplicateCount = duplicateCount.get();
      int currentReceivedCount = receivedCount.get();
      if ((currentReceivedCount % 100) == 0)
      {
         System.out.println("Received count: " + currentReceivedCount);
         System.out.println("Duplicate count: " + currentDuplicateCount);
         System.out.println("Total count: " + totalCount);
      }
      if((currentReceivedCount + currentDuplicateCount) == totalCount)
      {
         System.out.println("\n\n*****************************\n" +
               "  Test Finished\n" +
               "*****************************\n" +
               "  Received Count = " + currentReceivedCount + "\n" +
               "  Duplicate Count = " + currentDuplicateCount + "\n" +
               "*****************************\n\n");
      }
   }

   private synchronized boolean addToReceivedCount(int localClientInvokeCount)
   {
      boolean isDuplicate  = false;
      if(counterArray == null)
      {
         System.out.println("Error!  Have not received invoke for method 'totalCallCount', so can not process count.");
      }
      else
      {
         try
         {
            isDuplicate = counterArray[localClientInvokeCount];
            if (!isDuplicate)
            {
               counterArray[localClientInvokeCount] = true;
            }
         }
         catch(ArrayIndexOutOfBoundsException e)
         {
            System.err.println("Got ArrayIndexOutOfBoundsException");
            System.err.println("Counter array size = " + counterArray.length);
            System.err.println("Received count = " + localClientInvokeCount);
            e.printStackTrace();
         }
      }
      return isDuplicate;
   }

   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);
   }

   public class CompetedTimerTask extends TimerTask
   {
      private int numOfPasses = 0;

      /**
       * The action to be performed by this timer task.
       */
      public void run()
      {
         if(processingWork)
         {
            processingWork = false;
            numOfPasses = 0;
         }
         else
         {
            if(numOfPasses > 5)
            {
               serverProcessingComplete();
            }
            else
            {
               numOfPasses++;
            }
         }
      }

   }

}
