/**
 * 
 * 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.bdb;

import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
import com.sleepycat.je.Transaction;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.File;
import java.util.LinkedList;

/**
 * Some helper factory methods for creating default configured Berkeley DB objects
 *
 * @version $Revision: 1.1 $
 */
public class BDbHelper {
    private static final Log log = LogFactory.getLog(BDbHelper.class);
    private static ThreadLocal threadLocalTxn = new ThreadLocal();

    public static Environment createEnvironment(File dir) throws DatabaseException {
        dir.mkdirs();
        EnvironmentConfig envConfig = new EnvironmentConfig();
        envConfig.setAllowCreate(true);
        envConfig.setTransactional(true);
        return new Environment(dir, envConfig);
    }

    public static DatabaseConfig createDatabaseConfig() {
        DatabaseConfig config = new DatabaseConfig();
        config.setTransactional(true);
        config.setAllowCreate(true);
        return config;
    }

    /**
     * @return the current thread local transaction that is in progress or null if there is no
     *         transaction in progress
     */
    public static Transaction getTransaction() {
        LinkedList list = (LinkedList) threadLocalTxn.get();
        if (list != null && !list.isEmpty()) {
            return (Transaction) list.getFirst();
        }
        return null;
    }

    /**
     * Pops off the current transaction from the stack
     */
    public static Transaction popTransaction() {
        LinkedList list = (LinkedList) threadLocalTxn.get();
        if (list == null || list.isEmpty()) {
            log.warn("Attempt to pop transaction when no transaction in progress");
            return null;
        }
        else {
            return (Transaction) list.removeFirst();
        }
    }

    /**
     * Sets the current transaction, possibly including nesting
     */
    public static void pushTransaction(Transaction transaction) {
        LinkedList list = (LinkedList) threadLocalTxn.get();
        if (list == null) {
            list = new LinkedList();
            threadLocalTxn.set(list);
        }
        list.addLast(transaction);
    }

    public static int getTransactionCount() {
        LinkedList list = (LinkedList) threadLocalTxn.get();
        if (list != null) {
            return list.size();
        }
        return 0;
    }

    public static byte[] asBytes(long v) {
        byte[] data = new byte[8];
        data[0] = (byte) (v >>> 56);
        data[1] = (byte) (v >>> 48);
        data[2] = (byte) (v >>> 40);
        data[3] = (byte) (v >>> 32);
        data[4] = (byte) (v >>> 24);
        data[5] = (byte) (v >>> 16);
        data[6] = (byte) (v >>> 8);
        data[7] = (byte) (v >>> 0);
        return data;
    }

    public static byte[] asBytes(Long key) {
        long v = key.longValue();
        return asBytes(v);
    }

    public static long longFromBytes(byte[] data) {
        return (((long) data[0] << 56) +
                ((long) (data[1] & 255) << 48) +
                ((long) (data[2] & 255) << 40) +
                ((long) (data[3] & 255) << 32) +
                ((long) (data[4] & 255) << 24) +
                ((data[5] & 255) << 16) +
                ((data[6] & 255) << 8) +
                ((data[7] & 255) << 0));
    }

}
