// **********************************************************************
//
// Copyright (c) 1999
// Object Oriented Concepts, Inc.
// Billerica, MA, USA
//
// All Rights Reserved
//
// **********************************************************************

#include <OB/CORBA.h>
#include <OB/Timer.h>

#include <time.h>

#include <Factory_impl.h>
#include <Reaper.h>

// ----------------------------------------------------------------------
// DBReaper constructor and destructor
// ----------------------------------------------------------------------

DBReaper::DBReaper(CORBA_ORB_ptr orb, long expire, DBRecordImplPtrSeq& records)
    : expire_(expire), records_(records), orb_(CORBA_ORB::_duplicate(orb))
{
    interval_.tv_sec = 1;
    interval_.tv_usec = 0;

    //
    // Call `notify' in internal seconds.  true indicates that this
    // time period is relative, and not an absolute time.
    //
    activate(interval_, true);
}

// ----------------------------------------------------------------------
// DBReaper public member implementation
// ----------------------------------------------------------------------
//
// This method is called when the timer expires.
//
void
DBReaper::notify()
{
    time_t now = time(0);

    //
    // Go through each record expiring those more than expire_
    // seconds since last access.
    //
    CORBA_ULong i = 0;
    while(i < records_.length())
    {
	//
	// Record expired?
	//
	time_t diff = now - records_[i] -> access();
	if(diff > expire_)
	{
	    orb_ -> disconnect(records_[i]);
            records_.remove(i);
	}
	else
	{
	    ++i;
	}
    }

    //
    // Reactivate timer.
    //
    activate(interval_, true);
}
