/* JFox, the OpenSource J2EE Application Server
 *
 * Copyright (C) 2002 huihoo.com
 * Distributable under GNU LGPL license
 * See the GNU Lesser General Public License for more details.
 */

package org.jfox.tm;

import java.util.Hashtable;
import javax.naming.spi.ObjectFactory;
import javax.naming.Name;
import javax.naming.Context;
import javax.naming.Referenceable;
import javax.naming.Reference;
import javax.naming.NamingException;

import org.huihoo.jfox.system.ServiceSupport;
import org.huihoo.jfox.util.InitialContextHelper;

/**
 * 
 * @author <a href="mailto:young_yy@hotmail.com">Young Yang</a>
 */

public class TransactionManagerService extends ServiceSupport implements ObjectFactory, Referenceable {

  public final static String JNDI_NAME = "TransactionManager";
  private static TxManager tm = null;
  private static Context jndiContext = null;
  private static Reference ref = null;

  protected void doStart() throws Exception {
    jndiContext.rebind(JNDI_NAME,this);
  }

  protected void doStop() throws Exception {
    jndiContext.unbind(JNDI_NAME);
  }

  protected void doInit() throws Exception {
    jndiContext = InitialContextHelper.getInitialConext();
    tm = TxManager.getInstance();
  }

  protected void doDestroy() throws Exception {
    jndiContext = null;
    tm = null;
  }

  public void run() {
    // none
  }

  public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable environment) throws Exception {
    if(tm == null){
      tm = TxManager.getInstance();
    }
    return tm;
  }

  public synchronized Reference getReference() throws NamingException {
    if(ref == null) {
      ref = new Reference(getClass().getName(), getClass().getName(), null);
    }
    return ref;
  }

  public int getNumTransactions() {
    return tm.getNumTransactions();
  }

  public int getNumSuspendedTransactions() {
    return tm.getNumSuspendedTransactions();
  }

  /*
  public static TxManager lookup() throws NamingException {
    return (TxManager)javax.rmi.PortableRemoteObject.narrow(InitialContextHelper.getInitialConext().lookup(JNDI_NAME),TxManager.class);
  }
  */
  public static void main(String[] args) {

  }
}