/*
 *  PHEX - The pure-java Gnutella-servent.
 *  Copyright (C) 2001 - 2004 Gregor Koukkoullis ( phex <at> kouk <dot> de )
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 * 
 *  --- CVS Information ---
 *  $Id: HorizonTracker.java,v 1.2 2004/09/03 23:24:00 gregork Exp $
 */
package phex.common;

import java.util.HashSet;
import java.util.Set;
import java.util.TimerTask;

import phex.host.HostAddress;
import phex.msg.MsgPong;
import phex.utils.Logger;

/**
 * The class tracks the estimated size of the horizion in host count,
 * file count and file size. 
 * Tracking is done by keeping all seen Pongs from hosts up to a 
 * maximal count. After a certain time the collection is dropped and
 * recounting starts. The old values are lazy updated on each recount cycle.
 * The numbers are only a very rough estimation of the actual numbers.
 *
 */
public class HorizonTracker
{   
    /**
     * The maximal number of PONGS to track
     */
    private static final int MAX_PONG_COUNT = 10000;
    
    private static HorizonTracker instance = new HorizonTracker();
    
    /**
     * Indicates if the values of the last or current count should 
     * be used.
     */
    private boolean useLastCountValues;
    
    /**
     * A set to keep track of the already counted addresses. 
     */
    private Set/*<HostAddress>*/ trackedAddresses;
    
    private int currentHostCount;
    private long currentFileCount;
    private long currentFileSize;
    
    private int lastHostCount;
    private long lastFileCount;
    private long lastFileSize;
    
    /**
     * Singleton to make sure there is only one tracker!
     */
    private HorizonTracker()
    {
        Environment.getInstance().scheduleTimerTask( 
                new TrackerRefreshTimer(), TrackerRefreshTimer.TIMER_PERIOD,
                TrackerRefreshTimer.TIMER_PERIOD );
        
        useLastCountValues = false;
        trackedAddresses = new HashSet();
    }
    
    public static HorizonTracker getInstance()
    {
        return instance;
    }
    
    /**
     * @return Returns the lastFileCount.
     */
    public long getTotalFileCount()
    {
        
        return useLastCountValues ? lastFileCount : currentFileCount;
    }

    /**
     * @return Returns the lastFileSize.
     */
    public long getTotalFileSize()
    {
        return useLastCountValues ? lastFileSize : currentFileSize;
    }
    
    /**
     * @return Returns the lastHostCount.
     */
    public int getTotalHostCount()
    {
        return useLastCountValues ? lastHostCount : currentHostCount;
    }

    public synchronized void trackPong( MsgPong pong)
    {
        if ( trackedAddresses.size() > MAX_PONG_COUNT )
        {
            return;
        }
        HostAddress address = new HostAddress( pong.getIP(), pong.getPort() );

        boolean isAdded = trackedAddresses.add( address );
        if ( isAdded )
        { 
            currentFileCount += pong.getFileCount();
            currentFileSize += pong.getFileSizeInKB();
            currentHostCount ++;
        }
    }
    
    private synchronized void refreshTrackerStats()
    {
        lastHostCount = currentHostCount;
        lastFileCount = currentFileCount;
        lastFileSize = currentFileSize;
        
        useLastCountValues = true;
        
        currentFileCount = 0;
        currentFileSize = 0;
        currentHostCount = 0;
        
        trackedAddresses.clear();
    }
    
    private class TrackerRefreshTimer extends TimerTask
    {
        /**
         * The time after which the horizon calculation is updated.
         */
        private static final long TIMER_PERIOD = 15*60*1000;
        
        /**
         * @see java.util.TimerTask#run()
         */
        public void run()
        {
            try
            {
                refreshTrackerStats();
            }
            catch ( Throwable th )
            {
                Logger.logError( th );
            }
        }
    }
 }
