#include "graphicsLineModule.h"


// better this is static, then every module has a texture
// (we should do the same in the movie classes)
// also, we should have an array, and cycle through...

static int 				numTextures	= 3;
static lineTexture		offscreenTex[3];
static int 				texCounter;	
static bool 			bTexAllocated = false;
		

//-------------------------------------------
graphicsLineModule::graphicsLineModule(){
	module = new graphicsModuleBase();	// is this bad?
	
	if (!bTexAllocated){
		for (int i = 0; i < numTextures; i++){
			offscreenTex[i].allocate(1024,768, GL_RGB);
		}
		texCounter 			= 0;
		bTexAllocated 		= true;
	}
	
	setup();
}
		
//-------------------------------------------	
void graphicsLineModule::setup(){
	module->setup();
	box->setStartPointAngle(module->getStartPosition(), module->getStartAngle());	
}

//-------------------------------------------	
void graphicsLineModule::reset(){
	myTextureNum = texCounter++ % numTextures;
	printf("myTextureNum %i \n", myTextureNum);
	module->reset();	
	box->setStartPointAngle(module->getStartPosition(), module->getStartAngle());	
}

//-------------------------------------------	
bool graphicsLineModule::bAmIDone(){
	 return module->bAmIdone();
}

//-------------------------------------------	
void graphicsLineModule::update(){
	module->update();
	box->updatePts();
}

//-------------------------------------------	
bool graphicsLineModule::bHaveNewPoint(){
	return module->bHaveNewPoint();
}

//-------------------------------------------	
ofVec3f graphicsLineModule::getNewPoint(){
	ofVec3f pt = module->getNewPoint();
	return interpolatePt(box->ptsTranslated, pt.x/640.0f, 1 - (pt.y/480.0f));
}


//-------------------------------------------	
void graphicsLineModule::drawOffscreen(){

	// my laptop is pretty slow w/ loadScreenData at 1024x768
	// so perhaps 640 x 480 for now
	// should be interesting to try a pbuffer as an alternative
	// and then we can avoid the glClear call, which is slow (about 5fps) 
	
	ofSetColor(module->bgColor.x,module->bgColor.y, module->bgColor.z);
	ofRect(0,0,640,480);
	ofSetColor(0xff0000);
	module->draw();
	offscreenTex[myTextureNum].loadScreenData(0,0,640,480);

}


//-------------------------------------------	
void graphicsLineModule::draw(float offsetx, float offsety){
	
	// add the offset to the translation:
	ofVec3f ptsTransAndOffsetted[4];
	for (int i = 0; i < 4; i++){
		ptsTransAndOffsetted[i].set(box->ptsTranslated[i].x - offsetx, 	
									box->ptsTranslated[i].y - offsety, 0	
									);
	}
	
	ofSetColor(0xffffff);
	offscreenTex[myTextureNum].draw(ptsTransAndOffsetted);
	
	glPushMatrix();
		ofSetColor(0xffffff);
		box->draw(offsetx, offsety);
	glPopMatrix();
	
	/*	
	// draw the texture:
	ofSetColor(0xffffff);
	glBegin(GL_LINE_LOOP);
		for (int i = 0; i < 4; i++){
			glVertex2f(ptsTransAndOffsetted[i].x,ptsTransAndOffsetted[i].y);
		}
	glEnd();
	*/
	
	//module->draw();

}

