package edu.unl.dCache.namespace;

import java.util.Collection;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

public class TraceStatItem {

	// Internal data
    String  _name     = null;
    int     _requests = 0;
    int     _failed   = 0;
    int     _counter  = 0;
    
    // Locks
    Object  _f_lock   = null;
    Object  _s_lock   = null;
    
    
    // Holding buffer 
    private BlockingQueue<StatEntry> finishedBuffer = null;
    int     _size     = 1000;
    boolean _stats = false;
    
    public  TraceStatItem( String name ) {
    		_name = name;
    		_f_lock = new Object();
    		_s_lock = new Object();
    		finishedBuffer = new ArrayBlockingQueue<StatEntry>( _size );
    	}
    
    public void setStatistics( boolean stats ) {
    	_stats = stats;
    }
    
    public String getName( ) { return _name; }
    
    public void setSize( int size ) {
    		_size = size;
    }
    
    public int getSize( ) { return _size; }
    
    public StatEntry startRequest( Object data ) {
    		return new StatEntry( data );
    }
    
    public void failRequest( StatEntry se ) {
    		failRequest( se, null );
    }
    
    public void failRequest( StatEntry se, Object obj ) {
    		se.failRequest( obj );
    		try {
    			if (_stats) finishedBuffer.offer( se, 5, TimeUnit.MILLISECONDS );
    		} catch (InterruptedException ie) {
    			
    		}
    		synchronized (_f_lock) {
    			_failed ++;
    		}
    }
    
    public void finishRequest( StatEntry se ) { finishRequest( se, null ); }
    
    public void finishRequest( StatEntry se, Object obj ) {
    		se.finishRequest( obj );
    		try {
    			if (_stats) finishedBuffer.offer( se, 5, TimeUnit.MILLISECONDS );
    		} catch (InterruptedException ie) {
    			
    		}
    		synchronized (_s_lock) {
    			_requests ++;
    		}
    }
    
	public int drainTo( Collection<StatEntry> c ) {
    		synchronized (finishedBuffer) {
    			return (finishedBuffer).drainTo( c );
    		}
    }
    
    public String toString(){
        return _name+" "+_requests+" "+_failed ;
    }
}
