

package gov.va.med.cds.work;


import javax.resource.spi.work.WorkEvent;
import javax.resource.spi.work.WorkListener;


public class CompletingWorkListener
    implements
        WorkListener
{
    private int acceptedJobCount = 0;
    private int completedJobCount = 0;
    private int rejectedJobCount = 0;

    private Thread caller = null;


    public CompletingWorkListener( )
    {
        caller = Thread.currentThread();
    }


    public CompletingWorkListener( Thread aThread )
    {
        caller = aThread;
    }


    public void workAccepted( WorkEvent arg0 )
    {
        acceptedJobCount++ ;
        // TODO Auto-generated method stub
    }


    // interrupt the caller in case they are waiting(sleeping) for work to finish
    public void workCompleted( WorkEvent arg0 )
    {
        completedJobCount++ ;

        if ( allWorkIsComplete() && caller != null )
        {
            caller.interrupt();
        }
    }


    public void workRejected( WorkEvent arg0 )
    {
        rejectedJobCount++ ;
    }


    public void workStarted( WorkEvent arg0 )
    {
    }


    public boolean allWorkIsComplete( )
    {
        return ( acceptedJobCount + rejectedJobCount > completedJobCount ) ? false : true;
    }

}
