// **********************************************************************
//
// Copyright (c) 1999
// Object Oriented Concepts, Inc.
// Billerica, MA, USA
//
// All Rights Reserved
//
// **********************************************************************

#include <OB/CORBA.h>
#include <OB/Util.h>
#include <OB/Reactor.h>

#include <Receiver_impl.h>

#include <ctype.h>

// ----------------------------------------------------------------------
// Receiver constructor and desctructor
// ----------------------------------------------------------------------

Receiver_impl::Receiver_impl(Broadcaster_ptr server)
    : ReceiverBase_impl(server),
      input_(CORBA_string_dup(""))
{
    //
    // Register with the server
    //
    _register();

    //
    // Register with the reactor
    //
    OBReactor* reactor = OBReactor::instance();
    reactor -> registerHandler(this, OBEventRead, 0);
}

Receiver_impl::~Receiver_impl()
{
    //
    // Unregister with the reactor
    //
    OBReactor* reactor = OBReactor::instance();
    reactor -> unregisterHandler(this);
}

// ----------------------------------------------------------------------
// Print message
// ----------------------------------------------------------------------

void
Receiver_impl::print(const char* text)
{
    //
    // Remove active input line temporarily
    //
    for(CORBA_ULong i = 0 ; i < strlen(input_) ; i++)
	cout << "\b \b";

    //
    // Print the text
    //
    ReceiverBase_impl::print(text);

    //
    // Restore active input line
    //
    cout << input_ << flush;
}

// ----------------------------------------------------------------------
// ORBacus specific event handling
// ----------------------------------------------------------------------
 
void
Receiver_impl::handleStop()
{
    // Do nothing here
}

void
Receiver_impl::handleEvent(CORBA_ULong mask)
{
    assert(mask == OBEventRead);

    char c;
    cin.read(&c, 1);

    switch(c)
    {
    case '\b':
    {
	if(strlen(input_) > 0)
	{
	    input_[strlen(input_) - 1] = '\0';
	    cout << "\b \b" << flush;
	}
	break;
    }

    case '\n':
    {
	cout << c << flush;
	CORBA_String_var s = input_;
	input_[0] = '\0';
	parse(s);
	break;
    }

    default:
    {
	if(isprint(c))
	{
	    cout << c << flush;
	    input_ += c;
	}
	break;
    }
    }
}

