/*
 Copyright (C) 2002 Andreas Thiede ( a.thiede@berlin.de )

 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

#include <IO/Manager/IOBufferList.hpp>
#include <IO/Manager/IOBuffer.hpp>
#include <assert.h>

IOBufferList::IOBufferList()
    : IOObject( "", "IOBufferList" )
{
}

IOBufferList::IOBufferList( const IOBufferList & )
    : IOObject( "", "IOBufferList" )
{
    assert( "not implemented yet" == 0 );
}

void IOBufferList::operator=(const IOBufferList & )
{
    assert( "not implemented yet" == 0 );
}

void IOBufferList::init()
{
    mBlockNumber = 0;
}

void IOBufferList::finit()
{
    mBuffers.clear();
}

/* static */ IOBufferList * IOBufferList::create()
{
    IOBufferList * bl = new IOBufferList();

    return bl;
}

size_t IOBufferList::size()
{
    lock();
    
    size_t result = mBuffers.size();
    
    unlock();
    
    return result;
}

IOBuffer * IOBufferList::popFront( int milisecs )
{
    lock();
    
    if( size() == 0 ) {
    
        if( milisecs != -1 ) {
            
            wait( milisecs );
        }
        else {

            while( size() == 0 ) {
    
                wait();
            }
        }
    }
    
    IOBuffer *  buf = 0;
    
    if( size() > 0 ) {
    
        buf = mBuffers.front();
    
        if( buf ) {
    
            mBuffers.pop_front();
        
        }
    }
    
    unlock();  

    return buf;

}

int IOBufferList::pushBack( IOBuffer * buf )
{
    lock();

    if( buf != 0 ) {
    
        buf->retain();
    
        mBuffers.push_back( buf );

    }

    signal();
    
    unlock();
    
    return true;
}

int IOBufferList::pushBack( const char * data, int size )
{
    IOBuffer * buf = IOBuffer::initWithConstPointer( data, size, ++mBlockNumber );

    pushBack( buf );
    
    return true;
}

IOBufferList::~IOBufferList()
{
    finit();
}

