#include "GradientField.hxx"
#include "CatomWorld.hxx"
#include "CatomSim.hxx"
#include <limits.h>
#include "Network.hxx"

CODE_MODULE_DECLARATION( GradientField, GradientField );

MailboxID gradientMessagingBox = "gradientMessagingBox";

using namespace std;

GradientField::GradientField(catomID _hostCatom)
:CodeModule(_hostCatom) { signpost dprdebug_block_signpost(__FILE__,__LINE__,__FUNCTION__); 
	value = INT_MAX-1; sendAgain = false;
	if (hostCatom == 1000) {
		value = 0;
		sendAgain = true;
	}
}

void GradientField::simulationStart() { signpost dprdebug_block_signpost(__FILE__,__LINE__,__FUNCTION__); 
  worldPtr->catomHash[hostCatom]->C.mailboxManager.registerHandler(gradientMessagingBox,
		this,
		(msgHandlerPtr)&GradientField::gradientMsgHandler);
	worldPtr->catomHash[hostCatom]->alpha = 100;
}

void GradientField::newTick() { signpost dprdebug_block_signpost(__FILE__,__LINE__,__FUNCTION__); 
  //Catom *thisCatom = &(worldPtr->catomHash[hostCatom]->C);
  // CODE HERE
}

void GradientField::endTick() { signpost dprdebug_block_signpost(__FILE__,__LINE__,__FUNCTION__); 
	if (sendAgain) {
	  Catom *thisCatom = &(worldPtr->catomHash[hostCatom]->C);
	  Feature* featureMap = thisCatom->getFeatureMap();
	
		for (featureID fid = 1; fid <= NUM_FEATURES; fid++)
	   { //send to all neighbors
				GradientMessage* msg = new GradientMessage(gradientMessagingBox, value + 1);
				featureMap[fid].getNetworkAdapter()->sendMessage(msg);
	   }
		sendAgain = false;
	}
	if (hostCatom == 1000) sendAgain = true;
}

bool GradientField::gradientMsgHandler(GradientMessage* msg) { signpost dprdebug_block_signpost(__FILE__,__LINE__,__FUNCTION__); 
	if (msg->payload < value) {
		//worldPtr->oStart();
		//cout << "value was " << value << ", is now " << msg->payload << endl;
		//worldPtr->oEnd();
		value = msg->payload;
		sendAgain = true;
	}
  return false;
}
