/*
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999 Bull S.A.
 * Contact: jonas-team@objectweb.org
 * 
 * This library 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 any later version.
 * 
 * This library 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 library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * Initial developer(s): Philippe Durieux
 * Contributor(s): ______________________________________.
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.objectweb.jonas_ejb.container;

import java.rmi.NoSuchObjectException;
import java.rmi.RemoteException;
import javax.ejb.EJBException;
import javax.ejb.EJBLocalObject;
import javax.ejb.EJBObject;
import javax.ejb.NoSuchObjectLocalException;
import javax.ejb.RemoveException;
import javax.ejb.SessionSynchronization;
import javax.ejb.TransactionRequiredLocalException;
import javax.ejb.TransactionRolledbackLocalException;
import javax.transaction.InvalidTransactionException;
import javax.transaction.NotSupportedException;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;
import javax.transaction.Transaction;
import org.objectweb.jonas_timer.TimerEventListener;

/**
 * JStatefulSwitch is the implementation of JSessionSwitch dedicated to the
 * Stateful Session Bean.
 */
public class JStatefulSwitch extends JSessionSwitch {

    private int sessionId;
    private JStatefulContext bctx = null;
    private Transaction currTx = null;
    private JStatefulPool statefulPool;
    private boolean mustCommit = false;
    private boolean expired = false;
    private Transaction beanTx = null; // only for bean managed tx

    /**
     * constructor. 
     */
    public JStatefulSwitch(JStatefulFactory bf, JStatefulPool sfp) throws RemoteException {
	super(bf);
	TraceEjb.debugIc("JStatefulSwitch constructor");
	statefulPool = sfp;
    }

    // ===============================================================
    // TimerEventListener implementation
    // ===============================================================

    /**
     * The session timeout has expired
     */
    public synchronized void timeoutExpired(Object arg) {
	TraceEjb.verbose("stateful session timeout expired");
	mytimer = null;
	// Do not remove if still used in a transaction
	if (currTx != null) {
	    expired = true;
	} else {
	    if (bctx != null) {
		try {
		    bctx.setRemoved();
		} catch (RemoteException e) {
		    TraceEjb.verbose("timeout expired:"+e);
		} catch (RemoveException e) {
		    TraceEjb.verbose("timeout expired:"+e);
		}
	    }
	    noLongerUsed();
	}
    }

    // ===============================================================
    // other public methods
    // ===============================================================

    /**
     * At each business method, get a BeanContext to run it
     */
    public JSessionContext getICtx(Transaction tx) {
	TraceEjb.debugIc("JStatefulSwitch getICtx");

	// If session has been removed, we must throw NoSuchObject[Local]Exception
	// to the caller.
	if (sessionId == -1) {
	    throw new NoSuchObjectLocalException("This Session has been removed");
	}
	    
	// reload Context if it was passivated
	if (bctx == null) {
	    bctx = statefulPool.getContext(sessionId);
	}
	// Check Transaction
	checkTx(tx);

	return bctx;
    }

    /**
     * At each create, bind the Context to the transaction
     */
    public void bindICtx(Transaction tx, JStatefulContext bctx) {
	TraceEjb.debugIc("JStatefulSwitch bindICtx");
	// register this session to the session pool and get an Id
	sessionId = statefulPool.addContext(bctx);
	this.bctx = bctx;
	bctx.initSessionContext(this);
	// Check Transaction
	checkTx(tx);
    }

    /**
.     * Release the Context after use.
     */
    public void releaseICtx(Transaction tx) {
	TraceEjb.debugIc("JStatefulSwitch releaseICtx");

	// In case getICtx failed, bctx may be null.
	if (bctx == null) {
	    return;
	}

	// Stateful bean managed tx only
	setBeanTx();

	if (bctx.isMarkedRemoved()) {
	    stopTimer();
	    noLongerUsed();
	}
    }

    /**
     * This Session is no longer used:
     * - unexport Remote Object
     * - return the Session in the pool
     */
    public void noLongerUsed() {
	TraceEjb.debugIc("JStatefulSwitch noLongerUsed");

	// Unexport the EJBObject from the Orb
	if (remote != null) {
	    try {
		remote.unexportObject();
	    } catch (NoSuchObjectException e) {
		TraceEjb.error("Unexport Stateful Session failed: "+e);
	    }
	}

	// return the SessionSwitch in the pool.
	// will be reused for another Session.
	bf.removeEJB(this);

	// Remove this object.
	// Stateful session contexts are not pooled. (EJB spec.)
	statefulPool.removeContext(sessionId);
	bctx = null;
	sessionId = -1;
    }

    /**
     * End of Transaction
     */
    public void txCompleted() {
	TraceEjb.debugIc("JStatefulSwitch txCompleted");
	currTx = null;
	if (expired) {
	    timeoutExpired(null);	// try again
	}
    }

    /**
     * Returns True if bean is participating in a client transaction
     * This is used for remove on stateful session beans only.
     */
    public boolean isInTransaction() {
	return (currTx != null && !mustCommit);
    }

    public void setMustCommit(boolean mc) {
	mustCommit = mc;
    }


    // ===============================================================
    // private methods
    // ===============================================================

    /**
     * Keep the bean opened transaction for later use in other methods.
     * Stateful session bean may open a transaction and use it in other methods.
     * This is called at postInvoke
     */
    private void setBeanTx() {
	if (bf.isTxBeanManaged()) {
	    TraceEjb.debugTx("JStatefulSwitch setBeanTx");
	    try {
		beanTx = bf.getTransactionManager().suspend();
	    } catch (SystemException e) {
		TraceEjb.error("Cannot suspend transaction:"+e);
	    }
	}
    }

    /**
     * Check Transaction
     * throws only local exceptions, that will be converted later if remote access.
     * This is called at preInvoke
     */
    private void checkTx(Transaction tx) {

	// No check if no Synchro, except for bean managed transaction.
	if (bf.isSessionSynchro() == false) {
	    // Resume bean associated transaction.
	    // Stateful session bean may open a transaction and use it in other methods.
	    if (bf.isTxBeanManaged() && beanTx != null) {
		TraceEjb.debugTx("JStatefulSwitch resuming Bean Managed Tx");
		try {
		    bf.getTransactionManager().resume(beanTx);
		} catch (SystemException e) {
		    TraceEjb.error("Cannot resume transaction:"+e);
		} catch (InvalidTransactionException e) {
		    TraceEjb.error("Cannot resume transaction:"+e);
		}
	    } else {
		TraceEjb.debugTx("JStatefulSwitch No checkTx");
	    }
	    return;
	}

	if (tx == null) {
	    TraceEjb.debugTx("JStatefulSwitch checkTx (No Tx)");
	    if (currTx != null) {
		// A synchronized session must be called in the same transaction
		// between afterBegin and beforeCompletion calls
		TraceEjb.error("checkTx: Synchronized session called outside transaction context");
		throw new EJBException("Synchronized session called outside transaction context");
	    }
	} else {
	    TraceEjb.debugTx("JStatefulSwitch checkTx");
	    if (currTx == null) {
		// A new transaction starts on this synchronized session
		try {
		    tx.registerSynchronization(bctx);
		    SessionSynchronization ssbean = (SessionSynchronization) bctx.getInstance();
		    ssbean.afterBegin();
		} catch (RollbackException e) {
		    throw new TransactionRolledbackLocalException();
		} catch (SystemException e) {
		    throw new EJBException("checkTx error:"+e);
		} catch (RemoteException e) {
		    throw new EJBException("checkTx error:"+e);
		}
		currTx = tx;
	    } else {
		// A synchronized session must be called in the same transaction
		// between afterBegin and beforeCompletion calls
		if (tx.equals(currTx) == false) {
		    TraceEjb.error("checkTx: Synchronized session called in another transaction context");
		    throw new EJBException("Synchronized session called in another transaction context");
		}
	    }
	}
    }
}
