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

#include <iostream>
#include <errno.h>
#include <string.h>

#include "Flicker.hxx"

#include "CatomWorld.hxx"
#include "CatomSim.hxx"

CODE_MODULE_DECLARATION( Flicker, Flicker );

using namespace std;

int lastLinesFileTime = -1;
pthread_mutex_t linesFileMutex = PTHREAD_MUTEX_INITIALIZER;
ofstream *outfile = NULL;

void Flicker::simulationStart() {
  print_stats=(worldPtr->search_key_value_list("FLICKER_PRINT_STATS")=="true");
}

void Flicker::newTick() {
  //	worldPtr->catomHash[hostCatom]->C.setBatteryLife(rand() % 2);

  // SAMPLE: drawing a line in the world.
  worldPtr->addLine( hostCatom,Point3D(10,10,10),0,100,0);


  worldPtr->catomHash[hostCatom]->red = 251;
  worldPtr->catomHash[hostCatom]->green = 107;
  worldPtr->catomHash[hostCatom]->blue = 0;

}

void Flicker::endTick() {

  if (worldPtr->catomHash[hostCatom]->C.amOnFloor()) {
    worldPtr->catomHash[hostCatom]->red = 0;
    worldPtr->catomHash[hostCatom]->green = 104;
    worldPtr->catomHash[hostCatom]->blue = 190;
  }

  if (print_stats) {
    // should do appropriate locking here
    Point3D pos = worldPtr->catomHash[hostCatom]->C.getLocation();
    cout << "Flicker: " << hostCatom << " " << pos.getX() << " " << pos.getY()
         << " " << pos.getZ() << "\n";
  }

  /*
	CatomSim* catomSim = worldPtr->catomHash[hostCatom];
	Catom* hostCatom2 = &(worldPtr->catomHash[hostCatom]->C);

  catomSim->alpha = ((double)(rand() % 10000))/10000;
  //catomSim->alpha = 0.95;
  
  pthread_mutex_lock(&linesFileMutex);
  if(worldPtr->current_time > lastLinesFileTime) {
		lastLinesFileTime = worldPtr->current_time;
		
		char filename[256];
		sprintf(filename, "lines_%07d", (int)worldPtr->current_time + 1);
		
		if(outfile) {
		  outfile->close();
		  delete outfile;
		}
		
		outfile = new ofstream(filename, ios::out);
  }
  pthread_mutex_unlock(&linesFileMutex);
  
  
	(*outfile) << hostCatom2->getLocation().getX() << " "
		   << hostCatom2->getLocation().getY() << " "
		   << hostCatom2->getLocation().getZ() << " "
		   << hostCatom2->getLocation().getX()+2.0 << " "
		   << hostCatom2->getLocation().getY() << " "
		   << hostCatom2->getLocation().getZ() << endl;
  */
}
