/*
 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/IOInput.hpp>
#include <IO/Manager/IOStream.hpp>

IOInput::IOInput( const string & aName, IODeviceID anID )
 : IONode( aName, anID )
{
    setType("IOInput");

    init();
}

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

size_t IOInput::getNextBlockNumber()
{
    lock();
    
    size_t result = mBlockNumber++;
    
    unlock();
    
    return result;
}

bool IOInput::attachTo( IOStream * s,  bool shouldStart  )
{
    if( mStream ) {
        mStream->remProducer( this );
    }

    mStream = 0;
    
    if( s->addProducer( this ) ) {
        
        mStream = s;
        
       if( shouldStart && s->isStarted() ) {
        
            //printf( "IOInput::attachTo: starting %s\n", getName().c_str() );
            start();
        }

    }
    return mStream != 0;
}

bool IOInput::detachFromStream()
{
    if( isStarted() ) {
        stop();
    }

    if( mStream && mStream->remProducer( this ) ) {
        mStream = 0;
    }
    return mStream == 0;
}

bool IOInput::push( IOBuffer * ioBuf )
{
    if( mStream ) {
        return mStream->push( ioBuf );
    }
    return false;
}

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

void IOInput::finit()
{
}

