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

import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.jms.JMSException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.activemq.message.ActiveMQMessage;
import org.activemq.message.MessageAck;
import org.activemq.service.MessageIdentity;
import org.activemq.store.MessageStore;
import org.activemq.store.RecoveryListener;

/**
 * An implementation of {@link org.activemq.store.MessageStore} which uses a
 *
 * @version $Revision: 1.1.1.1 $
 */
public class VMMessageStore implements MessageStore {
    private static final Log log = LogFactory.getLog(VMMessageStore.class);

    protected Map messageTable;
    protected MessageIdentity lastMessageIdentity;

    public VMMessageStore() {
        this(new LinkedHashMap());
    }

    public VMMessageStore(LinkedHashMap messageTable) {
        this.messageTable = Collections.synchronizedMap(messageTable);
    }

    public synchronized void addMessage(ActiveMQMessage message) throws JMSException {
        messageTable.put(message.getJMSMessageID(), message);
        lastMessageIdentity = message.getJMSMessageIdentity();
    }

    public ActiveMQMessage getMessage(MessageIdentity identity) throws JMSException {
        String messageID = identity.getMessageID();
        return (ActiveMQMessage) messageTable.get(messageID);
    }

    public void removeMessage(MessageAck ack) throws JMSException {
        messageTable.remove(ack.getMessageID());
    }
    
    public void removeMessage(MessageIdentity msgId) throws JMSException {
        messageTable.remove(msgId.getMessageID());
    }

    public void recover(RecoveryListener listener) throws JMSException {
        for (Iterator iter = messageTable.values().iterator(); iter.hasNext();) {
            ActiveMQMessage msg = (ActiveMQMessage) iter.next();
            listener.recoverMessage(msg.getJMSMessageIdentity());
        }
    }

    public void start() throws JMSException {
    }

    public void stop() throws JMSException {
    }

    public void removeAllMessages() throws JMSException {
        messageTable.clear();
    }

}
