/*
 * JBoss, Home of Professional Open Source
 * Copyright 2005, JBoss Inc., and individual contributors as indicated
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.jboss.remoting;

import java.util.List;
import java.util.Map;
import org.jboss.logging.Logger;
import org.jboss.remoting.ClientInterceptor;
import org.jboss.remoting.InvokerCallbackHandler;
import org.jboss.remoting.InvokerLocator;
import org.jboss.remoting.invocation.InternalInvocation;
import org.jboss.remoting.transport.ClientInvoker;
import org.jboss.util.id.GUID;

import java.io.Serializable;



/**
 * ClientInvokerAdapter.java is a ClientInterceptor for the end of the
 * interceptor chain: it finds the right RemoteClientInvoker and calls
 * it. This is an mbean only for ease of configuration of interceptor
 * chains.
 *
 *
 * Created: Wed Apr 30 19:30:36 2003
 *
 * @author <a href="mailto:d_jencks@users.sourceforge.net">David Jencks</a>
 * @author <a href="mailto:telrod@e2technologies.net">Tom Elrod</a>
 * @version 1.0
 *
 * @jmx.mbean name="jboss.remoting:service=ClientInvokerAdapter"
 *            display-name="ClientInvokerAdapter"
 *            description="RemoteClientInvoker adapter that finds the RemoteClientInvoker based on the locator and calls it."
 * @jboss.service servicefile="remoting"
 * @jboss.xmbean
 */
public class ClientInvokerAdapter
   implements ClientInterceptor, Serializable
{

   private static Logger log = Logger.getLogger(ClientInvokerAdapter.class);
   transient ClassLoader cl;
   String internalSessionId = new GUID().toString();

   public ClientInvokerAdapter()
   {
      this(Thread.currentThread().getContextClassLoader());
   } // ClientInvokerAdapter constructor

   public ClientInvokerAdapter(ClassLoader cl)
   {
      this.cl = cl;
   } // ClientInvokerAdapter constructor


   // Implementation of org.jboss.remoting.ClientInterceptor

   /**
    * The <code>addListener</code> method
    *
    * @param invokerLocator an <code>InvokerLocator</code> value
    * @param string a <code>String</code> value
    * @param invokerCallbackHandler an <code>InvokerCallbackHandler</code> value
    * @exception Throwable if an error occurs
    */
   public void addListener(InvokerLocator locator, String subsystem, InvokerCallbackHandler callbackHandler) throws Throwable
   {
      ClientInvoker invoker = getClientInvoker(locator);
      // connect to the given client locator and add handler as listener
      InvokerLocator clientLocator = invoker.getClientLocator();
      if(clientLocator != null) // async callback
      {
            connect(clientLocator);
            invoke(new InvocationRequest(internalSessionId,
                                         subsystem,
                                         new InternalInvocation(InternalInvocation.ADDCLIENTLISTENER,
                                                                new Object[]{callbackHandler}),
                                         null,
                                         null,
                                         clientLocator));

            disconnect(clientLocator);//seems dangerous
        }
        // now call server to add listener
      invoke(new InvocationRequest(internalSessionId, subsystem, new InternalInvocation(InternalInvocation.ADDLISTENER, null), null, null, locator));


   }

   /**
    * The <code>removeListener</code> method
    *
    * @param invokerLocator an <code>InvokerLocator</code> value
    * @param string a <code>String</code> value
    * @param invokerCallbackHandler an <code>InvokerCallbackHandler</code> value
    * @exception Throwable if an error occurs
    */
   public void removeListener(InvokerLocator locator, String subsystem, InvokerCallbackHandler callbackHandler) throws Throwable
   {
      ClientInvoker invoker = getClientInvoker(locator);
        // connect to the given client locator and remove handler as listener
        InvokerLocator clientLocator = invoker.getClientLocator();
        if(clientLocator != null) // async callback
        {
            connect(clientLocator);
            invoke(new InvocationRequest(internalSessionId,
                                         subsystem,
                                         new InternalInvocation(InternalInvocation.REMOVECLIENTLISTENER,
                                                                new Object[]{callbackHandler}),
                                         null,
                                         null,
                                         clientLocator));

            disconnect(clientLocator);
        }
        // now call server to remove listener
      invoke(new InvocationRequest(internalSessionId, subsystem, new InternalInvocation(InternalInvocation.REMOVELISTENER, null), null, null, locator));
   }

   /**
    * The <code>getCallbacks</code> method
    *
    * @param invokerLocator an <code>InvokerLocator</code> value
    * @param string a <code>String</code> value
    * @return a <code>List</code> value
    * @exception Throwable if an error occurs
    */
   public List getCallbacks(InvokerLocator locator, String subsystem) throws Throwable
   {
      return (List)invoke(new InvocationRequest(internalSessionId, subsystem, new InternalInvocation(InternalInvocation.GETCALLBACKS, null), null, null, locator));

   }

   /**
    * The <code>invoke</code> method
    *
    * @param invokerLocator an <code>InvokerLocator</code> value
    * @param string a <code>String</code> value
    * @param string1 a <code>String</code> value
    * @param object an <code>Object</code> value
    * @param map a <code>Map</code> value
    * @return an <code>Object</code> value
    * @exception Throwable if an error occurs
    */
   public Object invoke(InvocationRequest invocation)
      throws Throwable
   {
      ClientInvoker invoker = getClientInvoker(invocation.getLocator());
      if (invoker.isConnected()==false)
      {
         if (log.isDebugEnabled())
         {
            log.debug("invoke called, but our invoker is disconnected, discarding and fetching another fresh invoker for: "+invoker.getLocator());
         }
         invoker.connect();
      }
      return invoker.invoke(invocation);
   }

   /**
    * The <code>connect</code> method
    *
    * @param invokerLocator an <code>InvokerLocator</code> value
    * @exception Exception if an error occurs
    */
   public void connect(InvokerLocator locator) throws Exception
   {
      ClientInvoker invoker = getClientInvoker(locator);
      invoker.connect();
   }

   /**
    * The <code>isConnected</code> method
    *
    * @param invokerLocator an <code>InvokerLocator</code> value
    * @return a <code>boolean</code> value
    */
   public boolean isConnected(InvokerLocator locator) throws Exception
   {
      ClientInvoker invoker = getClientInvoker(locator);
      return invoker.isConnected();
   }

   /**
    * The <code>disconnect</code> method
    *
    * @param locator an <code>InvokerLocator</code> value
    */
   public void disconnect(InvokerLocator locator) throws Exception
   {
      ClientInvoker invoker = getClientInvoker(locator);
      invoker.disconnect();
   }

   protected ClientInvoker getClientInvoker(InvokerLocator locator) throws Exception
   {
      return InvokerRegistry.createClientInvoker(locator);
   }

} // ClientInvokerAdapter
