/*
 * Modification History
 *
 * 2003-July-27    Jason Rohrer
 * Created.
 * Fixed indexing bugs.
 */



#include "ChannelReceivingThreadManager.h"



ChannelReceivingThreadManager::ChannelReceivingThreadManager()
    : mLock( new MutexLock() ),
      mThreadVector( new SimpleVector<ChannelReceivingThread *>() ),
      mStopSignal( false ) {

    this->start();
    }



ChannelReceivingThreadManager::~ChannelReceivingThreadManager() {
    mLock->lock();
    mStopSignal = true;
    mLock->unlock();

    this->join();

    mLock->lock();

    // destroy all remaining threads
    int numThreads = mThreadVector->size();

    for( int i=0; i<numThreads; i++ ) {
        delete *( mThreadVector->getElement( i ) );
        }
    delete mThreadVector;

    
    mLock->unlock();
    delete mLock;    
    }



void ChannelReceivingThreadManager::addThread(
    ChannelReceivingThread *inThread ) {

    mLock->lock();

    mThreadVector->push_back( inThread );

    mLock->unlock();
    }



void ChannelReceivingThreadManager::run() {
    
    char stopped;

    mLock->lock();
    stopped = mStopSignal;
    mLock->unlock();


    while( !stopped ) {
        // sleep for 10 seconds
        this->sleep( 10000 );
        
        char foundFinished = true;

        while( foundFinished ) {
            foundFinished = false;
            
            mLock->lock();
            
            int numThreads = mThreadVector->size();

            for( int i=0; i<numThreads && !foundFinished; i++ ) {
                
                ChannelReceivingThread *currentThread =
                    *( mThreadVector->getElement( i ) );

                if( currentThread->isFinished() ) {
                    delete currentThread;
                    mThreadVector->deleteElement( i );
                    foundFinished = true;
                    }
                }
            mLock->unlock();
            }

        mLock->lock();
        stopped = mStopSignal;
        mLock->unlock();
        }
    }

