#include "KLTTrackerProcessor.h"
#include "KLTCornerDetector.h"
#include "CanvasPointGrabber.h"
#include <memory>
#include <QAction>
#include <QtOpenGL>


KLTTrackerProcessor::KLTTrackerProcessor()
{
	_actionDetectFeatures = new QAction( QIcon(":/icons/interpret.png"), "Detect Features", this );
	_actionDetectFeatures->setObjectName( "actionDetectFeatures" );

	_cornerDetector = new KLTCornerDetector( CanvasPointGrabber::MAX_POINTS );

	QMetaObject::connectSlotsByName( this );
}

KLTTrackerProcessor::~KLTTrackerProcessor()
{
	// empty
}

void KLTTrackerProcessor::resize( int width, int height )
{
	_width	= width;
	_height = height;
}

void KLTTrackerProcessor::process( const unsigned char* original, unsigned char* processed )
{
	memcpy( processed, original, _width * _height );

	_cornerDetector->detect( processed, _width, _height );
}

QWidget* KLTTrackerProcessor::getPropertiesWidget( QWidget* parent )
{
	return NULL;
}

void KLTTrackerProcessor::setupToolBar( QToolBar* toolBar )
{
	toolBar->addAction( _actionDetectFeatures );
}

void KLTTrackerProcessor::decorateGL( Canvas* canvas )
{
	int numCorners = _cornerDetector->getNumCornersDetected();

	if( _cornerDetector->getNumCornersDetected() == 0 )
		return;

	int *points = _cornerDetector->getDetectedCorners();

	glPointSize( 3.0f );
	glBegin( GL_POINTS );
	glColor3f( 0.0, 1.0, 0.0 );

	for( int i = 0; i < numCorners; ++i )
	{
		glVertex2i( points[2*i], points[2*i + 1 ] );
	}

	glEnd();
}

bool KLTTrackerProcessor::onMousePress( Canvas* canvas, int x, int y )
{
	return false;
}

bool KLTTrackerProcessor::onMouseRelease( Canvas* canvas, int x, int y )
{
	return false;
}

void KLTTrackerProcessor::on_actionDetectFeatures_triggered()
{
	_cornerDetector->refreshDetection();
}
