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

import com.sleepycat.je.CursorConfig;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.LockMode;
import com.sleepycat.je.OperationStatus;
import com.sleepycat.je.SecondaryCursor;
import com.sleepycat.je.SecondaryDatabase;
import com.sleepycat.je.SecondaryKeyCreator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.jms.JMSException;

/**
 * @version $Revision: 1.1 $
 */
public class SequenceNumberCreator implements SecondaryKeyCreator {
    private static final Log log = LogFactory.getLog(SequenceNumberCreator.class);

    private long counter = 1;
    private ThreadLocal lastKeyStore = new ThreadLocal();
    private ThreadLocal deleteKeyStore = new ThreadLocal();

    public synchronized void initialise(SecondaryDatabase database) throws JMSException, DatabaseException {
        // lets calculate the size
        counter = queryLatestKeyInDatabase(database);
    }

    public boolean createSecondaryKey(SecondaryDatabase secondaryDatabase, DatabaseEntry keyEntry, DatabaseEntry valueEntry, DatabaseEntry resultEntry) throws DatabaseException {
        DatabaseEntry nextKey = (DatabaseEntry) deleteKeyStore.get();
        if (nextKey != null) {
            resultEntry.setData(nextKey.getData());
            deleteKeyStore.set(null);
        }
        else {
            long value = 1;
            synchronized (this) {
                value = ++counter;
            }
            //System.out.println("Creating new counter key of value: " + value);
            resultEntry.setData(BDbHelper.asBytes(value));
        }
        lastKeyStore.set(resultEntry);
        return true;
    }

    /**
     * @return the last primary key we created
     */
    public DatabaseEntry getLastKey() {
        return (DatabaseEntry) lastKeyStore.get();
    }

    /**
     * Sets the next primary key to return, such as doing a delete
     *
     * @param nextKey
     */
    public void setDeleteKey(DatabaseEntry nextKey) {
        this.deleteKeyStore.set(nextKey);
    }

    protected long queryLatestKeyInDatabase(SecondaryDatabase database) throws JMSException, DatabaseException {
        CursorConfig cursorConfig = null;
        SecondaryCursor cursor = null;
        try {
            cursor = database.openSecondaryCursor(BDbHelper.getTransaction(), cursorConfig);
            DatabaseEntry sequenceNumberEntry = new DatabaseEntry();
            DatabaseEntry keyEntry = new DatabaseEntry();
            DatabaseEntry valueEntry = new DatabaseEntry();
            OperationStatus status = cursor.getLast(sequenceNumberEntry, keyEntry, valueEntry, LockMode.DEFAULT);
            long answer = 1;
            if (status != OperationStatus.NOTFOUND) {
                if (status == OperationStatus.SUCCESS) {
                    answer = extractLong(sequenceNumberEntry);
                }
                else {
                    throw new JMSException("Invalid status code: " + status + " cannot read last sequence number");
                }
            }
            return answer;
        }
        finally {
            if (cursor != null) {
                try {
                    cursor.close();
                }
                catch (DatabaseException e) {
                    log.warn("Error closing cursor: " + e, e);
                }
            }
        }
    }

    protected long extractLong(DatabaseEntry entry) {
        return BDbHelper.longFromBytes(entry.getData());
    }
}
