/* JFox, the OpenSource J2EE Application Server
 *
 * Distributable under GNU LGPL license by gun.org
 * more details please visit http://www.huihoo.org/jfox
 */

package org.jfox.tm;

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

import org.jfox.framework.extra.ActiveComponent;
import org.jfox.jndi.InitialContextHelper;
import org.jfox.system.AbstractService;

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

public class UserTransactionManagerService extends AbstractService implements ActiveComponent, ObjectFactory, Referenceable {

    public final static String JNDI_NAME = "UserTransaction";
    private static ServerUserTransaction 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.getInitialContext();
        tm = ServerUserTransaction.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 = ServerUserTransaction.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) {

    }
}