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

import org.activemq.message.Packet;
import org.activemq.util.BitArrayBin;
import org.activemq.util.IdGenerator;
import org.activemq.util.LRUCache;

import javax.jms.JMSException;
import javax.jms.Message;
import java.util.LinkedHashMap;

/**
 * Provides basic audit functions for Messages
 *
 * @version $Revision: 1.1.1.1 $
 */
public class ActiveMQMessageAudit {
    private static final int DEFAULT_WINDOW_SIZE = 1024;
    private static final int MAXIMUM_PRODUCER_COUNT = 128;
    private int windowSize;
    private LinkedHashMap map;

    /**
     * Default Constructor windowSize = 1024, maximumNumberOfProducersToTrack = 128
     */
    public ActiveMQMessageAudit() {
        this(DEFAULT_WINDOW_SIZE, MAXIMUM_PRODUCER_COUNT);
    }

    /**
     * Construct a MessageAudit
     *
     * @param windowSize range of ids to track
     * @param maximumNumberOfProducersToTrack
     *                   number of producers expected in the system
     */
    public ActiveMQMessageAudit(int windowSize, final int maximumNumberOfProducersToTrack) {
        this.windowSize = windowSize;
        map = new LRUCache(maximumNumberOfProducersToTrack);
    }

    /**
     * Checks if this message has beeb seen before
     *
     * @param message
     * @return true if the message is a duplicate
     * @throws JMSException
     */
    public boolean isDuplicate(Message message) throws JMSException {
       return isDuplicate(message.getJMSMessageID());
    }


    /**
     * checks whether this messageId has been seen before and adds this messageId to the list
     *
     * @param id
     * @return true if the message is a duplicate
     */
    public boolean isDuplicate(String id) {
        boolean answer = false;
        String seed = IdGenerator.getSeedFromId(id);
        if (seed != null) {
            BitArrayBin bab = (BitArrayBin) map.get(seed);
            if (bab == null) {
                bab = new BitArrayBin(windowSize);
                map.put(seed, bab);
            }
            long index = IdGenerator.getCountFromId(id);
            if (index >= 0) {
                answer = bab.setBit(index, true);
            }
        }
        return answer;
    }
}
