/**
 * 
 * Copyright 2004 Hiram Chirino
 * Copyright 2004 Protique Ltd
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License. 
 * 
 **/
package org.activemq.store.jdbc;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.sql.Connection;

import javax.sql.DataSource;

/**
 * Helps keep track of the current transaction/JDBC connection.
 *
 * @version $Revision: 1.1 $
 */
public class TransactionContext {
    private static final Log log = LogFactory.getLog(TransactionContext.class);
    private static ThreadLocal threadLocalTxn = new ThreadLocal();
	private final DataSource dataSource;

    TransactionContext( DataSource dataSource ) {
		this.dataSource = dataSource;
    }
    
    /**
     * Pops off the current Connection from the stack
     */
    public static Connection popConnection() {
        Connection[] tx = (Connection[]) threadLocalTxn.get();
        if (tx == null || tx[0]==null) {
            log.warn("Attempt to pop connection when no transaction in progress");
            return null;
        }
        else {
        	Connection answer = tx[0];
        	tx[0]=null;
        	return answer;
        }
    }

    /**
     * Sets the current transaction, possibly including nesting
     */
    public static void pushConnection(Connection connection) {
        Connection[] tx = (Connection[]) threadLocalTxn.get();
        if (tx == null) {
            tx = new Connection[]{null};
            threadLocalTxn.set(tx);
        }
        if (tx[0] != null) {
            throw new IllegalStateException("A transaction is allready in progress");
        }
        tx[0] = connection;
    }

    /**
     * @return the current thread local connection that is associated
     *  with the JMS transaction or null if there is no 
     *  transaction in progress.
     */
    public static Connection peekConnection() {
        Connection tx[] = (Connection[]) threadLocalTxn.get();
        if (tx != null && tx[0]!=null ) {
            return tx[0];
        }
        return null;
    }

}
