#include "testApp.h"





//--------------------------------------------------------------
void testApp::setup(){	 
	
	camWidth 		= 320;	// try to grab at this size. 
	camHeight 		= 240;
	
	vidGrabber.setVerbose(true);
	vidGrabber.initGrabber(camWidth,camHeight);
	
	videoInverted 	= new unsigned char[camWidth*camHeight*3];
	videoTexture.allocate(camWidth,camHeight, GL_RGB);
	
	bRecording = false;
	frameNewCounter = 0;
	ofSetFrameRate(60);
}


//--------------------------------------------------------------
void testApp::update(){
	
	ofBackground(100,100,100);
	
	vidGrabber.grabFrame();
	
	if (vidGrabber.isFrameNew()){
		
		frameNewCounter++;
		
		int totalPixels = camWidth*camHeight*3;
		unsigned char * pixels = vidGrabber.getPixels();
		
		if (bRecording == true){
			unsigned char * frame = new unsigned char [camWidth * camHeight * 3];
			memcpy(frame, pixels, camWidth * camHeight * 3);
			recordedFrames.push_back(frame);
		} else {
			if (recordedFrames.size() > 0){
				int whichFrame = frameNewCounter % recordedFrames.size(); //(int)ofRandom(0,recordedFrames.size());
				videoTexture.loadData(recordedFrames[whichFrame], camWidth,camHeight, GL_RGB);
			}
		}
	
	
	}
	


}

//--------------------------------------------------------------
void testApp::draw(){
	ofSetColor(0xffffff);
	vidGrabber.draw(20,20);
	videoTexture.draw(20+camWidth,20,camWidth,camHeight);
}


//--------------------------------------------------------------
void testApp::keyPressed  (int key){ 
	
	// in fullscreen mode, on a pc at least, the 
	// first time video settings the come up
	// they come up *under* the fullscreen window
	// use alt-tab to navigate to the settings
	// window. we are working on a fix for this...
	
	if (key == 's' || key == 'S'){
		vidGrabber.videoSettings();
	}
	
	
	if (key == 'r'){
		bRecording = !bRecording;	
		
		if (bRecording == true){
			// clear recording! 
			for (int i = 0; i < recordedFrames.size(); i++){
				delete [] recordedFrames[i];
			}
			recordedFrames.clear();
		}
		
		if (!bRecording){
			frameNewCounter = 0;	
		}
	}
	
	
}


//--------------------------------------------------------------
void testApp::keyReleased(int key){ 
	
}

//--------------------------------------------------------------
void testApp::mouseMoved(int x, int y ){
	
}

//--------------------------------------------------------------
void testApp::mouseDragged(int x, int y, int button){
	
}

//--------------------------------------------------------------
void testApp::mousePressed(int x, int y, int button){
	
}

//--------------------------------------------------------------
void testApp::mouseReleased(int x, int y, int button){

}

//--------------------------------------------------------------
void testApp::windowResized(int w, int h){

}
