/*
 *  mesbus.cpp
 *  (C) gsd 2001
 *  ver 1.1
 */
 
// #include <sstream>      // for standard
#include <strstream>       // for g++

#include <algorithm>
   
#include "mesbus.h"

using namespace std;

// the key sequencer for m_busid
long CMessageBus::sm_busid = 0;

// the router 
map<long, CMessageBus*> CMessageBus::sm_router;

// constructor: assign a uniq id to "m_busid", and register "this" at router
CMessageBus::CMessageBus() : m_busid(sm_busid)
{
    ++sm_busid;
    sm_router[m_busid] = this;
}

// destructor: deregister from router
CMessageBus::~CMessageBus()
{
    sm_router.erase( m_busid);
}

// send a message to id
bool CMessageBus::send( long id, string message)
{
    if ( sm_router.find( id )  !=  sm_router.end() )
    {
        sm_router[id]->receive( m_busid, message);
        return true;
    }
    else
    {
        return false;
    }
}

// receive a message
void CMessageBus::receive( long sender_id, string message)
{
    cout << "Device id = " << m_busid
         << ", sender = "  << sender_id 
         << ", received = " << message << endl;
}

string CMessageBus::getsid() const
{
//    ostringstream os;
    ostrstream  os;
    os << getid();
    return os.str();                                                        
}

void CMessageBus::printrouter()
{
    map<long, CMessageBus*>::const_iterator ci;

    for( ci = sm_router.begin(); ci != sm_router.end(); ++ci)
    {
        cout << ci->first << '\t' << ci->second << endl;
    } 
}

/*
void CMessageBus::pRouterEntry(const CMessageBus *p)
{
    cout << p->first << '\t' << p->second << endl;
}

void CMessageBus::pRouter()
{
    for_each( sm_router.begin(); sm_router.end(); mem_fun(pRouterEntry));
}
*/