#include "CanvasPointGrabber.h"
#include "Canvas.h"
#include <QMouseEvent>

CanvasPointGrabber::CanvasPointGrabber( Canvas *canvas ) 
{
	_canvas = canvas;

	_numPoints = 0;
	_currentState = STATE_EMPTY;
}

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

void CanvasPointGrabber::startGrabbing()
{
	_numPoints = 0;
	_currentState = STATE_GRABBING;

	connect( _canvas, SIGNAL(mousePressed(QMouseEvent*)), this, SLOT(mousePressed(QMouseEvent*)) );
}

void CanvasPointGrabber::stopGrabbing()
{
	if( _currentState != STATE_GRABBING )
		return;

	disconnect( _canvas, SIGNAL(mousePressed(QMouseEvent*)), this, SLOT(mousePressed(QMouseEvent*)) );

	if( _numPoints == 0 )
	{
		_currentState = STATE_EMPTY;
	}
	else 
	{
		_currentState = STATE_READY;
	}
}

void CanvasPointGrabber::decorateGL( Canvas* canvas )
{
	for( int i = 0; i < _numPoints; ++i )
	{
		canvas->renderText( _points[i].x(), _points[i].y(), QString::number( i ) );
	}	
}

void CanvasPointGrabber::mousePressed( QMouseEvent* event )
{
	if( event->button() == Qt::RightButton )
	{
		// remove the last clicked point from the list:
		if( _numPoints > 0 )
			--_numPoints;
	}
	else
	{
		// append the newly clicked point to the list:
		_points[_numPoints++] = event->pos();

		if( _numPoints == MAX_POINTS )
			stopGrabbing();
	}

	_canvas->updateGL();
}
