///////////////////////////////////////////////////////////////////////////////
//                                                                           //
// Copyright (C) 2006 by Intel Coproration and Carnegie Mellon University    //
// Contacts: casey.j.helfrich @ intel.com                                    //
//           bdr @ cs.cmu.edu                                                //
//                                                                           //
///////////////////////////////////////////////////////////////////////////////

#include <iostream>

#include "TestMessaging.hxx"

CODE_MODULE_DECLARATION( TestMessaging, TestMessaging );


#include "Catom.hxx"
#include "CatomSim.hxx"
#include "CatomWorld.hxx"
#include "Network.hxx"

MailboxID testMessagingBox = "testMessagingBox";
MailboxID testMessagingFastBox = "testMessagingFastBox";

using namespace std;

void TestMessaging::simulationStart() {
  //worldPtr->oStart(); cerr << "simulationStart()\n" << endl;
  worldPtr->catomHash[hostCatom]->C.mailboxManager.registerHandler(testMessagingBox,
								   this,
								   (msgHandlerPtr)&TestMessaging::testHandler);

  // *** Use of the 'fast' messaging style is not for you; contact BDR before use ***
  worldPtr->catomHash[hostCatom]->C.mailboxManager.registerHandler(testMessagingFastBox,
								   this,
								   (msgHandlerPtr)&TestMessaging::testFastHandler,
								   false);
}

void TestMessaging::endTick() {
  if((random() % 1000) == 0) {
    // Send message to random neighbor
    Feature* featureMap = worldPtr->catomHash[hostCatom]->C.getFeatureMap();
    ExampleMessage* msg;
    
    featureID startfid = random() % NUM_FEATURES;
    featureID fid = startfid;
    do {
      if(fid == 0)
	fid++;
      
      worldPtr->oStart();
      if(random() % 2) {
	msg = new ExampleMessage(testMessagingBox, 42);
	cerr << "Catom " << hostCatom << " sending regular message at tick " << worldPtr->current_time << endl;
      } else {
	msg = new ExampleMessage(testMessagingFastBox, 42);
	cerr << "Catom " << hostCatom << " sending fast message at tick " << worldPtr->current_time << endl;
      }
      worldPtr->oEnd();
      
      if(featureMap[fid].getNetworkAdapter()->sendMessage(msg))
	return;
      
      fid = (fid+1) % NUM_FEATURES;
    } while (fid != startfid);
  }
}

bool TestMessaging::testHandler(ExampleMessage* msg) {
  worldPtr->oStart();
  cerr << hostCatom << "'s testHandler called at tick " << worldPtr->current_time << endl;
  worldPtr->oEnd();
  return false;
}

// Use of the 'fast' messaging style is not for you; contact BDR before use
bool TestMessaging::testFastHandler(ExampleMessage* msg) {
  worldPtr->oStart();
  cerr << hostCatom << "'s testFastHandler called at tick " << worldPtr->current_time << endl;
  worldPtr->oEnd();
  return false;
}

StateFile::Module* TestMessaging::StateFileConstructor() {
  return NULL;
}
