// =====================================================================
//  $Id: TOutputObjectSocket.cc,v 1.1.1.1 2003/06/27 02:56:41 goiwai Exp $
//  $Name: CLDAQ-1-06-02 $
// =====================================================================
#include "TOutputObjectSocket.hh"
#include "TStreamableObject.hh"
#include "TObjectFilter.hh"

TOutputObjectSocket::TOutputObjectSocket( const Tstring& hostname, Tint port )
  : TObjectSocket( port ), TOutputObjectStream( tSocketStream ), 
    theServerName( hostname ), theHostInformation( 0 )
{
  initialize();
}

TOutputObjectSocket::TOutputObjectSocket( Tint port )
  : TObjectSocket( port ), TOutputObjectStream( tSocketStream ), 
    theServerName( "localhost" ), theHostInformation( 0 )
{
  initialize();
}

TOutputObjectSocket::TOutputObjectSocket( TObjectFilter* filter, const Tstring& hostname, Tint port )
  : TObjectSocket( port ), TOutputObjectStream( filter, tSocketStream ), 
    theServerName( hostname ), theHostInformation( 0 )
{
  initialize();
}

TOutputObjectSocket::TOutputObjectSocket( TObjectFilter* filter, Tint port )
  : TObjectSocket( port ), TOutputObjectStream( filter, tSocketStream ), 
    theServerName( "localhost" ), theHostInformation( 0 )
{
  initialize();
}

TOutputObjectSocket::~TOutputObjectSocket()
{
  CloseServer();
}

Tvoid TOutputObjectSocket::initialize()
{
  theHostInformation = gethostbyname( theServerName.c_str() );
  if ( theHostInformation == 0 ) {
    perror( "TOutputObjectSocket::initialize" );
    exit( -errno );
  }
  theAddress.sin_family = PF_INET;
  theAddress.sin_port = htons( (TUshort)thePortNumber );
  theAddress.sin_addr.s_addr =
    *( (unsigned long *)( *( theHostInformation -> h_addr_list ) ) );

  OpenServer();
  Tsocklen_t len = (Tsocklen_t)( Tsizeof( theAddress ) );

  if ( connect( theServerDescriptor, (struct sockaddr *)&theAddress, len ) == -1 )
    perror( "TOutputObjectSocket::initialize" );


  return;
}

Tint TOutputObjectSocket::Write( TStreamableObject& object )
{
  theLastDataSize = theDataSize;
  theDataSize = 0;

  if ( HasFilter() ) {
    theDataSize = theObjectFilter -> Filtering( object, this );
  } else {
    theDataSize = object.Record( this );
  }

  theTotalDataSize += theDataSize;
  return( theDataSize );
}
