/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999 Bull S.A.
 * Contact: jonas-team@ow2.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
 *
 * --------------------------------------------------------------------------
 * $Id: JEntitySwitchCST.java 15428 2008-10-07 11:20:29Z sauthieg $
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.lib.ejb21;

import javax.ejb.EJBException;
import javax.ejb.ObjectNotFoundException;
import javax.ejb.TransactionRolledbackLocalException;
import javax.transaction.Status;
import javax.transaction.SystemException;
import javax.transaction.Transaction;

import org.ow2.jonas.deployment.ejb.EntityDesc;


import org.objectweb.util.monolog.api.BasicLevel;

/**
 * Container Serialized Transacted (CST) lock-policy.
 * Transaction Isolation managed by the container.
 * All transactions are serialized.
 * @author Philippe Durieux
 */
public class JEntitySwitchCST extends JEntitySwitch {

    /**
     * unique EntityContext
     */
    protected JEntityContext itContext = null;

    /**
     * empty constructor. Object is initialized via init() because it is
     * implemented differently according to jorm mappers.
     */
    public JEntitySwitchCST() {
        lockpolicy = EntityDesc.LOCK_CONTAINER_SERIALIZED_TRANSACTED;
    }

    protected void initpolicy(JEntityFactory bf) {
        // Setting this to true (if CMP2, !prefetch, and !shared)
        // would be equivalent to the CRW policy.
        lazyregister = false;
    }

    protected JEntityContext getContext4Tx(Transaction tx) {
        return itContext;
    }

    protected void setContext4Tx(Transaction tx, JEntityContext ctx) {
        if (TraceEjb.isDebugContext()) {
            TraceEjb.context.log(BasicLevel.DEBUG, "set itContext=" + ctx);
        }
        itContext = ctx;
    }

    protected void removeContext4Tx(Transaction tx) {
        if (TraceEjb.isDebugContext()) {
            TraceEjb.context.log(BasicLevel.DEBUG, "unset itContext=" + itContext);
        }
        itContext = null;
    }

    /**
     * Wait until I'm allowed to work on this instance.
     * Transaction isolation may be done here, depending on lock-policy.
     * @param tx Transaction
     */
    public void waitmyturn(Transaction tx) {
        if (tx == null) {
            // Must wait in case of TX
            while (runningtx != null) {
                if (TraceEjb.isDebugSynchro()) {
                    TraceEjb.synchro.log(BasicLevel.DEBUG, ident + "mapICtx IH: WAIT end IT");
                }
                waiters++;
                try {
                    wait(deadlockTimeout);
                    if (TraceEjb.isDebugSynchro())
                            TraceEjb.synchro.log(BasicLevel.DEBUG, ident + "mapICtx IH: NOTIFIED");
                } catch (InterruptedException e) {
                    if (TraceEjb.isDebugSynchro())
                            TraceEjb.synchro.log(BasicLevel.DEBUG, ident + "mapICtx IH: INTERRUPTED");
                } catch (Exception e) {
                    throw new EJBException("JEntitySwitch synchronization pb", e);
                } finally {
                    waiters--;
                }
            }
        } else {
            int waitcount = 0;
            Transaction lastrunning = null;
            // Must wait in case of other TX, or if non tx methods are using instance
            while (countIH > 0 || (runningtx != null && !tx.equals(runningtx))) {
                if (countIH > 0) {
                    if (TraceEjb.isDebugSynchro())
                        TraceEjb.synchro.log(BasicLevel.DEBUG, ident + "mapICtx IT: WAIT end IH");
                } else {
                    if (TraceEjb.isDebugSynchro())
                        TraceEjb.synchro.log(BasicLevel.DEBUG, ident + "mapICtx IT: WAIT end IT");
                    // deadlock detection
                    blockedtx.add(tx);
                    if (waitcount > 0 && runningtx.equals(lastrunning) && bf.isDeadLocked(runningtx)) {
                        blockedtx.remove(tx);
                        try {
                            tx.setRollbackOnly();
                        } catch (SystemException e) {
                            TraceEjb.logger.log(BasicLevel.ERROR, ident
                                    + "getICtx IT: unexpected exception setting rollbackonly");
                        }
                        TraceEjb.logger.log(BasicLevel.WARN, ident + "getICtx IT: transaction rolled back");
                        throw new TransactionRolledbackLocalException("possible deadlock");
                    }
                    lastrunning = runningtx;
                }
                waitcount++;
                waiters++;
                try {
                    wait(deadlockTimeout);
                    if (TraceEjb.isDebugSynchro())
                            TraceEjb.synchro.log(BasicLevel.DEBUG, ident + "mapICtx IT: NOTIFIED");
                } catch (InterruptedException e) {
                    if (TraceEjb.isDebugSynchro())
                            TraceEjb.synchro.log(BasicLevel.DEBUG, ident + "mapICtx IT: INTERRUPTED");
                } catch (Exception e) {
                    throw new EJBException("JEntitySwitch synchronization pb", e);
                } finally {
                    waiters--;
                    if (lastrunning != null) {
                        blockedtx.remove(tx);
                    }
                }
                // If transaction has been rolledback or set rollback only, give
                // up.
                int status = Status.STATUS_ROLLEDBACK;
                try {
                    status = tx.getStatus();
                } catch (SystemException e) {
                    TraceEjb.logger.log(BasicLevel.ERROR, ident
                            + "getICtx IT: unexpected exception getting transaction status");
                }
                switch (status) {
                case Status.STATUS_MARKED_ROLLBACK:
                case Status.STATUS_ROLLEDBACK:
                case Status.STATUS_ROLLING_BACK:
                    TraceEjb.logger.log(BasicLevel.WARN, ident + "getICtx IT: transaction rolled back");
                    throw new TransactionRolledbackLocalException("rollback occured while waiting");
                }
            }
        }

    }

    /**
     * Try to bind a JEntityContext if none already bound. Called by finder
     * methods. This is actually kind of optimization.
     * Can be bypassed if problems: just return false.
     * @param tx - the Transaction object
     * @param bctx The Entity Context
     * @param simple True if simple finder method
     * @return true if context has been bound to this EntitySwitch.
     */
    public synchronized boolean tryBindICtx(Transaction tx, JEntityContext bctx, boolean simple) throws ObjectNotFoundException {
        if (shared) {
            // In case of shared=true (and select4update) don't try to cache an instance too early.
            // This sometimes leaded to problems.
            // Must check if removed and simple finder
            if (simple && getContext4Tx(tx) != null && getContext4Tx(tx).isMarkedRemoved()) {
                throw new ObjectNotFoundException("Instance is currently being removed");
            }
            TraceEjb.context.log(BasicLevel.DEBUG, "shared => don't cache too early");
            return false;
        }
        return super.tryBindICtx(tx, bctx, simple);
    }

    /**
     * try to passivate instances
     * @param store not used for this policy
     * @param passivate always true for this policy
     * @return result of operation: (not really used here)
     * ALL_DONE = instances passivated
     * NOT_DONE = not all passivated
     */
    public synchronized int passivateIH(boolean store, boolean passivate) {
        if (isdetached) {
            return NOT_DONE;
        }
        // Don't passivate too recent instances to avoid problems at create
        long ttd = estimestamp - System.currentTimeMillis();
        if (ttd > 0) {
            TraceEjb.context.log(BasicLevel.DEBUG, "too recent");
            return NOT_DONE;
        }

        // Only 1 instance with this policy
        JEntityContext jec = getContext4Tx(null);
        if (countIH == 0 && runningtx == null && countIT == 0) {
            if (jec != null) {
                if (jec.isMarkedRemoved()) {
                    // should not go here ?
                    TraceEjb.context.log(BasicLevel.ERROR, "marked removed");
                    discardContext(null, true, true);
                    return ALL_DONE;
                }
                if (TraceEjb.isDebugContext()) {
                    TraceEjb.context.log(BasicLevel.DEBUG, "passivate: " + jec);
                }
                if (!jec.passivate()) {
                    TraceEjb.context.log(BasicLevel.DEBUG, ident + " not passivated ");
                    return NOT_DONE;
                }
                if (jec.getMyTx() != null) {
                    TraceEjb.context.log(BasicLevel.WARN, "Will forget Tx???");
                }
                // Will be pooled only if min-pool-size not reached in free list.
                bf.releaseJContext(jec, 1);
                removeContext4Tx(null);
                // notify waiters for new instances
                if (waiters > 0) {
                    notifyAll();
                }
            }
            // look if we can destroy the objects
            if (inactivityTimeout > 0) {
                ttd = inactivityTimeout + estimestamp - System.currentTimeMillis();
                if (ttd <= 0) {
                    detachPk();
                    estimestamp = System.currentTimeMillis();
                }
            }

            return ALL_DONE;
        }
        return NOT_DONE;
    }

    /**
     * Instance is ready to use for new transaction.
     */
    public synchronized void endIH() {
        TraceEjb.synchro.log(BasicLevel.ERROR, ident);
        return; // NEVER
    }

    /**
     * @return State of this instance. State values are 0=in-tx, 1=out-tx, 2=idle,
     *         3=passive, 4=removed. we don't synchronize this method to avoid
     *         jadmin blocks
     */
    public int getState() {
        if (itContext != null) {
            if (itContext.isMarkedRemoved()) {
                return 4;
            } else {
                if (runningtx != null) {
                    return 0;
                } else {
                    return inDirtyList ? 1 : 2;
                }
            }
        }
        return 3;
    }

}
