/**
 * 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: JEntitySwitchCRC.java 15428 2008-10-07 11:20:29Z sauthieg $
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.lib.ejb21;

import javax.ejb.EJBException;
import javax.ejb.NoSuchObjectLocalException;
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 read committed lock policy.
 * transactions are serialized by the container.
 * Accesses outside transaction read committed state.
 * @author Philippe Durieux
 */
public class JEntitySwitchCRC extends JEntitySwitch {

    /**
     * EntityContext for transacted requests
     */
    protected JEntityContext itContext = null;

    /**
     * EntityContext for non-transacted requests
     */
    protected JEntityContext ihContext = null;


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

    protected void initpolicy(JEntityFactory bf) {
        lazyregister = false;
    }

    protected JEntityContext getContext4Tx(Transaction tx) {
        JEntityContext ctx = null;
        if (tx == null) {
            ctx = ihContext;
        } else {
            ctx = itContext;
        }
        return ctx;
    }

    /**
     * @param tx The Transaction
     * @param the JEntityContext used for this tx
     */
    protected void setContext4Tx(Transaction tx, JEntityContext ctx) {
        if (tx == null) {
            ihContext = ctx;
        } else {
            itContext = ctx;
        }
    }

    /**
     *
     */
    protected void removeContext4Tx(Transaction tx) {
        // free this Context
        if (tx == null) {
            ihContext = null;
        } else {
            itContext = null;
        }
    }

    public void waitmyturn(Transaction tx) {

        // Synchronization.
        if (tx != null) {
            // Must wait in case of TX or if instance has been modified outside
            // transaction.
            // Don't wait transactions if 1 instance per transaction.
            int waitcount = 0;
            Transaction lastrunning = null;
            while (runningtx != null && !tx.equals(runningtx)) {
                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", e);
                    }
                    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", e);
                    }
                } catch (Exception e) {
                    throw new EJBException("JEntitySwitch synchronization pb", e);
                } finally {
                    waiters--;
                    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", e);
                }
                switch (status) {
                case Status.STATUS_MARKED_ROLLBACK:
                case Status.STATUS_ROLLEDBACK:
                case Status.STATUS_ROLLING_BACK:
                    if (TraceEjb.isVerbose()) {
                        TraceEjb.logger.log(BasicLevel.WARN, ident + "getICtx IT: transaction rolled back");
                    }
                    throw new TransactionRolledbackLocalException("rollback occured while waiting");
                }
            }
        }
    }

    /**
     * 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) {

        long ttd = estimestamp - System.currentTimeMillis();
        if (ttd > 0) {
            TraceEjb.context.log(BasicLevel.DEBUG, "too recent");
            return NOT_DONE;
        }

        int icount = 0;

        // Instance used when no transaction.
        JEntityContext jec = ihContext;
        if (jec != null && countIH == 0) {
            if (TraceEjb.isDebugContext()) {
                TraceEjb.context.log(BasicLevel.DEBUG, "passivate: " + jec);
            }
            if (jec.passivate()) {
                // Will be pooled only if min-pool-size not reached in free list.
                bf.releaseJContext(jec, 1);
                ihContext = null;
                icount++;
            }
        }

        // Instance used for transactions
        jec = itContext;
        if (jec != null && runningtx == null && countIT == 0) {
            if (TraceEjb.isDebugContext()) {
                TraceEjb.context.log(BasicLevel.DEBUG, "passivated: " + jec);
            }
            if (jec.passivate()) {
                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);
                itContext = null;
                icount++;
            }
        }

        // notify waiters for new instances
        if (icount > 0 && waiters > 0) {
            notifyAll();
        }

        // all instances passivated
        if (icount == 2) {
            // 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;
    }

    public synchronized void endIH() {
        TraceEjb.synchro.log(BasicLevel.ERROR, ident);
        // Not used.
    }

    /**
     * @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 (ihContext != null) {
            if (ihContext.isMarkedRemoved()) {
                return 4;
            } else {
                if (itContext == null) {
                    return 2;
                }
            }
        }
        if (itContext != null) {
            if (itContext.isMarkedRemoved()) {
                return 4;
            } else {
                if (runningtx != null) {
                    return 0;
                } else {
                    return 2;
                }
            }
        }
        return 3;
    }

}
