#include "TickOrganizer.h"
#include "Constants.h"


TickOrganizer::TickOrganizer()
    : ReferenceCounter()
{
    queue = new TickQueue();
    workerCount = NUM_TICK_WORKERS;
    workers = new TickWorker * [ workerCount ];
    for( int i = 0; i < workerCount; i++ )
        workers[ i ] = new TickWorker( queue );
}

TickOrganizer::~TickOrganizer()
{
    queue->requestExit();
    for( int i = 0; i < workerCount; i++ )
    {
        workers[ i ]->warteAufThread( 10000 );
        workers[ i ]->ende();
        workers[ i ]->release();
    }
    queue->release();
    delete[] workers;
}

void TickOrganizer::nextTick()
{
    queue->startNextTick( &tickSources );
    bool notWaiting = 0;
    do
    {
        queue->waitForEmpty();
        for (int i = 0; i < workerCount; i++)
            notWaiting |= !workers[i]->isWaiting();
    } while (notWaiting);
}

void TickOrganizer::addTickSource( Block *zBlock )
{
    tickSources.add( zBlock );
}

void TickOrganizer::removeTickSource( Block *zBlock )
{
    int index = 0;
    for( Framework::Iterator<Block *> it = tickSources.getIterator(); it; it++, index++ )
    {
        if( it == zBlock )
        {
            tickSources.remove( index );
            return;
        }
    }
}