/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.apache.activeblaze.wire;

import org.apache.activeblaze.BaseService;
import org.apache.activeblaze.util.BitArrayBin;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Checks for duplicates
 */
public class PacketAudit extends BaseService {
    public static final int DEFAULT_MAX_AUDIT_DEPTH = 2048;
    public static final int DEFAULT_MAX_CHANNELS = 256;
    private LinkedHashMap<Buffer, BitArrayBin> cache;
    private int maxChannels = DEFAULT_MAX_CHANNELS;
    private int maxAuditDepth = DEFAULT_MAX_AUDIT_DEPTH;

    /**
     * @see org.apache.activeblaze.BaseService#doShutDown()
     */
    public void doShutDown() throws Exception {
        this.cache = null;
    }

    /**
     * @see org.apache.activeblaze.BaseService#doStart()
     */
    @SuppressWarnings("serial")
    public void doStart() throws Exception {
        if (this.cache == null) {
            this.cache = new LinkedHashMap<Buffer, BitArrayBin>() {
                protected boolean removeEldestEntry(Map.Entry<Buffer, BitArrayBin> eldest) {
                    return size() > getMaxChannels();
                }
            };
        }
    }

    /**
     * @return the maxChannels
     */
    public int getMaxChannels() {
        return this.maxChannels;
    }

    /**
     * @param maxChannels the maxChannels to set
     */
    public void setMaxChannels(int maxChannels) {
        this.maxChannels = maxChannels;
    }

    /**
     * tests for a duplicate message
     *
     * @return true if a duplicate message
     */
    public boolean isDuplicate(Packet packet) {
        return isDuplicate(packet.getProducerId(), packet.getMessageSequence());
    }

    /**
     * tests for a duplicate message
     *
     * @return true if a duplicate message
     */
    public boolean isDuplicate(String producerId, long id) {
        if (producerId != null) {
            return isDuplicate(new Buffer(producerId), id);
        }
        return false;
    }

    /**
     * tests for a duplicate message
     */
    public boolean isDuplicate(Buffer key, long id) {
        boolean result = false;
        LinkedHashMap<Buffer, BitArrayBin> theCache = this.cache;
        if (theCache != null) {
            synchronized (theCache) {
                BitArrayBin bin = theCache.get(key);
                if (bin == null) {
                    bin = new BitArrayBin(getMaxAuditDepth());
                    theCache.put(key, bin);
                }
                result = bin.setBit(id, true);
            }
        }
        return result;
    }

    /**
     * @return the maxAuditDepth
     */
    public int getMaxAuditDepth() {
        return this.maxAuditDepth;
    }

    /**
     * @param maxAuditDepth the maxAuditDepth to set
     */
    public void setMaxAuditDepth(int maxAuditDepth) {
        this.maxAuditDepth = maxAuditDepth;
    }

    /**
     * @see org.apache.activeblaze.BaseService#doInit()
     */
    @Override
    protected void doInit() throws Exception {
        // TODO Auto-generated method stub
    }

    /**
     * @see org.apache.activeblaze.BaseService#doStop()
     */
    @Override
    protected void doStop() throws Exception {
        // TODO Auto-generated method stub
    }
}
