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

Canvas::Canvas( QWidget *parent )
	: QGLWidget( parent ), _font( "Arial", 12, QFont::Normal ), _fontMetrics( _font )
{
	_processor = 0;
	_imageWidth = 320;
	_imageHeight = 240;
	_screenWidth = 320;
	_screenHeight = 240;
}

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

void Canvas::setProcessor( Processor *processor )
{
	_processor = processor;
}

void Canvas::setFrameBuffer( int width, int height, GLenum format, const unsigned char* buffer )
{
	_imageWidth = width;
	_imageHeight = height;
	_format = format;
	_buffer = buffer;
//	updatePixelZoom();
}

int Canvas::textWidth( const QString &str ) const
{
	return _fontMetrics.width( str ) / _pixelZoom;
}

void Canvas::renderText( int imgX, int imgY, const QString &str )
{
	glColor3f( 1, 0, 0 );
	QGLWidget::renderText( imgX, _imageHeight - imgY, 0, str, _font );
}

void Canvas::initializeGL()
{
	glClearColor( 0.0, 0.0, 0.0, 1.0 );
	glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );
	glHint( GL_LINE_SMOOTH_HINT, GL_NICEST );
	glEnableClientState( GL_VERTEX_ARRAY );
	glEnableClientState( GL_NORMAL_ARRAY );
	glEnable( GL_DEPTH_TEST );
}

void Canvas::resizeGL( int width, int height )
{
// 	_screenWidth = width;
// 	_screenHeight = height;
// 	updatePixelZoom();
// 
// 	glViewport( 0, 0, _screenWidth / _pixelZoomX, _screenHeight / _pixelZoomY );
	glViewport( 0, 0, width, height );

	glColor3ub( 240, 30, 30 );
	renderText( 0, 0, " " );
}

void Canvas::paintGL()
{
	glDepthFunc( GL_LEQUAL );
	glClearColor( 0.0f, 0.0f, 0.0f, 1.0f );
	glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

	glMatrixMode( GL_PROJECTION );
	glLoadIdentity();
	//gluOrtho2D( 0.0, _imageWidth / _pixelZoom, 0.0, _imageHeight / _pixelZoom );
	gluOrtho2D( 0.0, _imageWidth, 0.0, _imageHeight );
	
	glMatrixMode( GL_MODELVIEW );
	glLoadIdentity();

	if( _buffer )
	{
	//	glPixelZoom( _pixelZoom, _pixelZoom );
		glDepthMask( GL_FALSE );
		glDrawPixels( _imageWidth, _imageHeight, _format, GL_UNSIGNED_BYTE, _buffer );
		glDepthMask( GL_TRUE );
	}

	if( _processor )
		_processor->decorateGL( this );
}

void Canvas::mousePressEvent( QMouseEvent* event )
{
	emit mousePressed( event );
}

void Canvas::mouseReleaseEvent( QMouseEvent* event )
{
	emit mouseReleased( event );
}
