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

package org.ow2.jonas.lib.ejb21;

import java.util.Iterator;
import java.util.LinkedList;
import javax.naming.Context;
import javax.transaction.Synchronization;
import javax.transaction.Transaction;

import org.ow2.jonas.lib.ejb21.jorm.JormFactory;

import org.objectweb.jorm.api.PMapper;
import org.objectweb.medor.eval.prefetch.api.PrefetchCache;
import org.objectweb.util.monolog.api.BasicLevel;

/**
 * This class is a listener on the transaction. It is registered as
 * a Synchronization on the current transaction. It holds the list of all
 * instances that are possibly modified during the transaction.
 * @author Philippe Durieux
 * @author Alexei Novakov (fix ConcurrentModification issue)
 */
public class TxListener implements Synchronization {

    private JEntityFactory bf;
    private Transaction tx;

    /**
     * list of contexts to be stored on disk.
     */
    private LinkedList ctxList = new LinkedList();
    private LinkedList additionalContexts = new LinkedList();
    private  boolean inStoreInstances = false;

    /**
     * constructor
     * @param bf ref on the Bean Factory
     * @param tx associated Transaction
     */
    public TxListener(JEntityFactory bf, Transaction tx) {
        if (TraceEjb.isDebugTxlistener()) {
            TraceEjb.txlistener.log(BasicLevel.DEBUG, "");
        }
        this.bf = bf;
        this.tx = tx;
    }

    /**
     * Synchronizes all instances on disk.
     * This must be called before every SQL request (finder) or at beforeCompletion().
     * We must be in the good transaction context here, and with the correct
     * component environment (java:comp).
     */
    public synchronized void storeInstances() {
        if (TraceEjb.isDebugTxlistener()) {
            TraceEjb.txlistener.log(BasicLevel.DEBUG, "");
        }
        inStoreInstances = true;
        storeInstances(ctxList);
        while (!additionalContexts.isEmpty()) {
            LinkedList lst = new LinkedList();
            lst.addAll(additionalContexts);
            additionalContexts.clear();
            storeInstances(lst);
            ctxList.addAll(lst);
        }
        inStoreInstances = false;
    }

    /**
     * Remove an instance from the list
     */
    public synchronized void removeInstance(JEntityContext ec) {
        if (TraceEjb.isDebugTxlistener()) {
            TraceEjb.txlistener.log(BasicLevel.DEBUG, "");
        }
        if (! ctxList.remove(ec)) {
            if (! additionalContexts.remove(ec)) {
                TraceEjb.txlistener.log(BasicLevel.WARN, "Not in the list");
            }
        }
    }

    /**
     * Add a new Context in the list.
     * @param ec the JEntityContext to synchronize
     */
    public synchronized void addInstance(JEntityContext ec) {
        if (TraceEjb.isDebugTxlistener()) {
            TraceEjb.txlistener.log(BasicLevel.DEBUG, "");
            TraceEjb.txlistener.log(BasicLevel.DEBUG,ec.getEntityFactory().getEJBName());
        }
        if (inStoreInstances) {
            additionalContexts.addLast(ec);
        } else {
            ctxList.addLast(ec);
        }
    }

    // -------------------------------------------------------------------
    // 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.
     * The Bean's state must be stored on the persistent storage before
     * the completion of the transaction.
     */
    public void beforeCompletion() {
        if (TraceEjb.isDebugTxlistener()) {
            TraceEjb.txlistener.log(BasicLevel.DEBUG, "");
        }

        // Set classloader for getting the right component context
        ClassLoader old = Thread.currentThread().getContextClassLoader();
        Thread.currentThread().setContextClassLoader(bf.myClassLoader());

        Context bnctx = bf.setComponentContext();
        storeInstances();
        bf.resetComponentContext(bnctx);
        Thread.currentThread().setContextClassLoader(old);
    }

    /**
     * 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) {
        if (TraceEjb.isDebugTxlistener()) {
            TraceEjb.txlistener.log(BasicLevel.DEBUG, "");
        }

        // Send afterCompletion on each Context.
        synchronized (this) {
            for (Iterator i = ctxList.iterator(); i.hasNext(); ) {
                JEntityContext ec = (JEntityContext) i.next();
                ec.afterCompletion(status);
            }
        }

        // Invalid the prefetch cache
        if (bf instanceof JormFactory) {
            PMapper mapper = ((JormFactory) bf).getMapper();
            PrefetchCache pc = mapper.getPrefetchCache();
            if (pc != null) {
                pc.invalidatePrefetchBuffer(tx);
            }
        }

        // remove this in the tx HashMap.
        bf.removeTxListener(tx);
    }

    private void storeInstances(LinkedList contexts) {
        if (TraceEjb.isDebugTxlistener()) {
            TraceEjb.txlistener.log(BasicLevel.DEBUG, "");
        }

        for (Iterator i = contexts.iterator(); i.hasNext(); ) {
            JEntityContext ec = (JEntityContext) i.next();
            ec.beforeCompletion();
            if (TraceEjb.isDebugTxlistener()) {
                TraceEjb.txlistener.log(BasicLevel.DEBUG, "ec.beforeCompletion() on"+ ec.getEntityFactory().getEJBName());
            }
        }
    }
}
