/*
 * 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): ____________________________________.
 * Contributor(s):
 * 01/11/06 Christophe Ney cney@batisseurs.com for Lutris Technologies
 *          Added ResourceManagerListener mechanism to remove ThreadData
 *          dependency.
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */


package org.objectweb.jonas.dbm;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Hashtable;
import java.util.LinkedList;
import javax.sql.XAConnection;
import javax.transaction.Synchronization;
import javax.transaction.Transaction;
import org.objectweb.jonas.common.Log;
import org.objectweb.jonas_tm.TransactionImpl;
import org.objectweb.transaction.api.ResourceManagerEvent;
import org.objectweb.util.monolog.api.Logger;
import org.objectweb.util.monolog.api.BasicLevel;

/**
 * This class represents a connection stored in the pool.
 * It may be in different states:
 * - available and reuseable for this user (open=0, tx=null)
 * - reusable for the same transaction, not already committed (open=?, tx!=null)
 * - still open, but not involved in a Tx (open=1, tx=null)
 * These 2 cases must be considered: close after commit, commit after close.
 * We cannot suppose what shema the user will use and we must handle both correctly.
 */
public class PoolItem implements ResourceManagerEvent, Synchronization {
    private static int count = 0;
    public XAConnection xaConn; // the pooled connection
    public String user;         // the user name
    public int open;            // >0 if connection is open
    public Transaction tx;  // transaction the connection is involved with
    public Transaction enlistedInTx; /// current transaction in case of late enlistment
    public long lMaxAgeMillis;  // When it is expected to die
    public int number;
    private Pool pool; // needed for synchronization
    private Logger logger = null;
    
    /*
     * constructor used by newConnection()
     */
    public PoolItem(Pool pool, XAConnection xac, String user, long maxage) {
        this.pool = pool;
        this.xaConn = xac;
        this.user = user;
        open = 0;
        lMaxAgeMillis = System.currentTimeMillis() + maxage;
	number = count++;
	logger = Log.getLogger(Log.JONAS_DBM_PREFIX);
    }

    /*
     * string form for debugging
     */
    public String toString() {
	Integer i = new Integer(number);
	return i.toString();
    }

    /**
     *  implementation of resource manager event
     */
    public void enlistConnection(Transaction transaction) throws javax.transaction.SystemException  {
        // this works only with jonas.jdbc_xa package since it
        // returns always the same object ( should return a new one according to
        // the jdbc specifications
        try {
            xaConn.getConnection().setAutoCommit(false);
            // the tx value of the pool item does not match with the enlisted value !?
            enlistedInTx = transaction;
            // enlist the resource
            transaction.enlistResource(xaConn.getXAResource());
        } catch (javax.transaction.RollbackException e) {
            throw new javax.transaction.SystemException("Unexpected RollbackException exception: "+e.getMessage());
        } catch (java.sql.SQLException e) {
            throw new javax.transaction.SystemException("Unexpected SQL exception: "+e.getMessage());
        }
    }

    /**
     *  synchronization implementation
     */
    public void beforeCompletion() {
        // nothing to do
    }

    
    /**
     *  synchronization implementation
     */
    public void afterCompletion(int status) {
	if (tx == null ) {
            logger.log(BasicLevel.ERROR, "NO TX!");
	}
	pool.freeConnections(tx != null ? tx : enlistedInTx);
    }
}
