/*
 * WatchList.java
 *
 * Created on June 14, 2006, 4:06 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package sidnet.core.misc;

import java.util.LinkedList;
import jist.runtime.JistAPI;
import jist.swans.net.NetMessage;

/**
 *
 * @author Oliviu Ghica
 */
public class WatchList {
    public class Item
    {
        public int id;
        public byte ttl;
        public long registrationTimeStamp;
        public long expirationTimeStamp;
        
        public Item(int id, byte ttl, long registrationTimeStamp, long expirationTimeStamp)
        {
            this.id                    = id;
            this.ttl                   = ttl;
            this.registrationTimeStamp = registrationTimeStamp;
            this.expirationTimeStamp   = registrationTimeStamp;
        }
    }
    private LinkedList<Item> packetList;
    private long expirationInterval;
    
    /** Creates a new instance of WatchList */
    public WatchList(long expirationInterval) {
        packetList = new LinkedList();
        this.expirationInterval = expirationInterval;
    }
    
    public boolean isDuplicate(int id, byte ttl)
    {
        long currentTimeStamp = JistAPI.getTime();
        purgeExpired(currentTimeStamp);
        
        if (!exists(id, ttl))
        {
            packetList.add(new Item(id, ttl, currentTimeStamp, currentTimeStamp + expirationInterval));
            return false;
        }
        return true;
    }
    
    public boolean isDuplicate(int id)
    {
        return isDuplicate(id, (byte)-1);
    }
    
    private boolean exists(int id, byte ttl)
    {
        for (Item item:packetList)
            if (item.id == id && (item.ttl != -1 && item.ttl == ttl || item.ttl == -1))
                return true;
        return false;
    }
    
    private void purgeExpired(long currentTimeStamp)
    {
        LinkedList<Item> expirationList = new LinkedList<Item>();
        
        for (Item item: packetList)
            if (currentTimeStamp > item.expirationTimeStamp)
                expirationList.add(item);
        
        for (Item item: expirationList)
            packetList.remove(item);
    }
}
