/*
 * 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 Coq, Philippe Durieux
 * Contributor(s): ______________________________________.
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.objectweb.jonas_ejb.container;

import java.io.Serializable;
import java.rmi.RemoteException;
import javax.ejb.SessionBean;
import javax.ejb.SessionSynchronization;
import javax.ejb.EJBObject;
import javax.ejb.RemoveException;
import javax.ejb.SessionContext;
import javax.naming.Context;
import javax.transaction.Transaction;
import javax.transaction.Synchronization;
import javax.transaction.Status;
import javax.transaction.SystemException;

/**
 * This class extends JSessionContext in case of Stateful Session Bean.
 */
public class JStatefulContext extends JSessionContext implements Synchronization {

    /**
     * the bean instance implements SessionSynchronization interface
     * @serial
     */
    boolean synchro = false;
    boolean timedout = false;

    // ------------------------------------------------------------------
    // constructors
    // ------------------------------------------------------------------

    /**
     * Constructs a JStatefulContext
     */
    public JStatefulContext(JSessionFactory bf, SessionBean sb, boolean sync) {
	super(bf, sb);
	TraceEjb.debugIc("JStatefulContext constructor");
	synchro = sync;
    }

    // -------------------------------------------------------------------
    // Synchronization implementation
    // -------------------------------------------------------------------

   /** 
     * This beforeCompletion method is called by the transaction 
     * manager prior to the start of the transaction completion process.
     * This method executes in the transaction context of the calling 
     * thread.
     */
    public void beforeCompletion() {
	TraceEjb.debugTx("JStatefulContext.beforeCompletion()");

	if (synchro) {
	    Context bnctx = bf.setComponentContext();
	    try {
		SessionSynchronization ss = (SessionSynchronization) getInstance();
		ss.beforeCompletion();
	    } catch (RemoteException e) {
		TraceEjb.error("JStatefulContext.beforeCompletion exception:", e);
	    } finally {
		bf.resetComponentContext(bnctx);
	    }
	}
    }

    /** 
     * The afterCompletion method is called by the transaction 
     * manager after the transaction is committed or rolled back. 
     * This method executes without a transaction context.
     *
     * @param status The status of the transaction completion.
     */
    public void afterCompletion(int status) {
	TraceEjb.debugTx("JStatefulContext.afterCompletion() ");

	if (synchro) {
	    Context bnctx = bf.setComponentContext();
	    try {
		SessionSynchronization ss = (SessionSynchronization) getInstance();
		ss.afterCompletion(status == Status.STATUS_COMMITTED);
	    } catch (RemoteException e) {
		TraceEjb.error("JStatefulContext.afterCompletion exception:", e);
	    } finally {
		bf.resetComponentContext(bnctx);
	    }
	}

	// Let the StatefulSwitch now that transaction is over and that it can
	// now dispose of this Context for another transaction.
	// no need to be in the correct component context ?
	JStatefulSwitch jss = (JStatefulSwitch) bs;
	jss.txCompleted();

	// The timeout has expired during the transaction. We can now remove
	// this session.
	if (timedout) {
	    TraceEjb.verbose("JStatefulContext: timeout expired during the transaction");
	    timedout = false;
	    // TODO
	    // ((JStatefulSession)ejbObject).forceSessionRemove();
	}
    }

    // ------------------------------------------------------------------
    // Other methods
    // ------------------------------------------------------------------

    /**
     * set this instance as removed
     */
    public void setRemoved() throws RemoteException, RemoveException {
	TraceEjb.debugIc("JStatefulContext setRemoved");

	// Cannot remove a stateful session inside a transaction
	JStatefulSwitch jss = (JStatefulSwitch) bs;
	if (jss.isInTransaction()) {
	    throw new RemoveException("Cannot remove a statefull session inside a transaction");
	}

	// Call ejbRemove on instance
	// Assume that if this method is transacted (container transaction only), this
	// transaction will be committed by the container (always true normally)
	SessionBean sb = (SessionBean) instance;
	sb.ejbRemove();

	// Set a flag to finish remove at postInvoke.
	// getEJBObject should work in ejbRemove.
	// => we do this only after ejbRemove call.
	ismarkedremoved = true;
    }

}
