#include "testApp.h"


//--------------------------------------------------------------
void testApp::setup(){	 
	ofBackground(0,0,0);
	ofEnableAlphaBlending();
	ofSetFrameRate(30);
	//ofEnableSmoothing();
	ofSeedRandom();
	ofSetVerticalSync(true);
	
	cwidth = 320;
    cheight = 240;
	threshold = 60;
	bLearnBakground = true;    

	vidGrabber.initGrabber( cwidth, cheight );
	colorImg.allocate( cwidth, cheight );
	grayImg.allocate( cwidth, cheight );
	bgImg.allocate( cwidth, cheight );
	debug=true;
}

//--------------------------------------------------------------
void testApp::update(){
	vidGrabber.grabFrame();
	
	if( vidGrabber.isFrameNew() ) {
        colorImg = vidGrabber.getPixels();
        //colorImg.mirror( true, false ); //overhead cam       
        colorImg.mirror( false, true ); //built-in cam
        grayImg = colorImg;
     
        if( bLearnBakground ) {
            bgImg = grayImg;
            bLearnBakground = false;
        }    

        grayImg.absDiff( bgImg );
        grayImg.blur( 11 );
        grayImg.threshold( threshold );

        //findContures( img, minSize, maxSize, nMax, inner contours yes/no )
        contourFinder.findContours( grayImg, 800,20000, 10, false );
        blobTracker.trackBlobs( contourFinder.blobs );
    }
}

//--------------------------------------------------------------
void testApp::draw(){
	
	if(debug)
	{
		printDebug();
	}
	
}

//--------------------------------------------------------------
void testApp::reactToBlobs()
{
	//blobReacting--------
	for(int b=0;b<blobTracker.blobs.size();b++)
	{
	}
}
//-------------------------------------------------------------
void testApp::printDebug()
{
	ofSetColor( 0xffffff );
	
	colorImg.draw( 20,200 );
	grayImg.draw( 360,200 );
	
	blobTracker.draw( 20,200 );
	
	ofDrawBitmapString( "[space] to learn background\n[+]/[-] to adjust threshold", 20,510 );   
}
//--------------------------------------------------------------
void testApp::keyPressed  (int key){ 
	 if( key == ' ' ) {
        bLearnBakground = true;
    } else if( key == '-' ) {
        threshold = MAX( 0, threshold-1 );
    } else if( key == '+' || key == '=' ) {
        threshold = MIN( 255, threshold+1 );
    } else if(key == 'd'){
		debug=!debug;
	}
}

//--------------------------------------------------------------
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(){

}
