/***************************** LICENSE START ***********************************

 Copyright 2012 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#include <QCursor>
#include <QtOpenGL>
#include <iostream>
#include <math.h>

#include "GLWidget.h"
#include "MtInputEvent.h"
#include "MagPlusService.h"

//We need it beacuse somewehere in X, which is coming through MagPlusService.h, 
//CursorShape is defined!
#undef CursorShape

Mt::Key getMtKey(int qtKey)
{
	static map<int,Mt::Key> key;
	if ( key.empty() )
	{
		key[Qt::Key_Left]  	= Mt::Key_Left;
		key[Qt::Key_Up] 	= Mt::Key_Up;
		key[Qt::Key_Right]	= Mt::Key_Right;
		key[Qt::Key_Down] 	= Mt::Key_Down;
	}
	if(key.find(qtKey) == key.end())
	{
		key[qtKey]=Mt::Key_Unknown;
	}

	return key[qtKey];
}

Qt::CursorShape getQtCursorShape(const string& cursorName)
{
	static map<string,Qt::CursorShape> cursor;
	if ( cursor.empty() )
	{
		cursor["Arrow"]		= Qt::ArrowCursor;
		cursor["Cross"]  	= Qt::CrossCursor;
		cursor["OpenHand"]  	= Qt::OpenHandCursor;
		cursor["ClosedHand"]  	= Qt::ClosedHandCursor;
		cursor["SizeVer"]  	= Qt::SizeVerCursor;
		cursor["SizeHor"]  	= Qt::SizeHorCursor;
		
	}
	if(cursor.find(cursorName) == cursor.end())
	{
		cursor[cursorName]=Qt::ArrowCursor;
	}

	return cursor[cursorName];
}


GLWidget::GLWidget(const QGLFormat &format,QWidget *parent) : QGLWidget(format,parent)
{
	  setAutoFillBackground(false);//empty
}

GLWidget::~GLWidget()
{
    // makeCurrent();
    // glDeleteLists(object, 1);
}

void GLWidget::initializeGL()
{
	cout << "initializeGL" << endl;

	setAutoBufferSwap(false);

	const char* version = (const char*) glGetString(GL_VERSION);
	
	if(version == 0)
	{
		cout << "Unrecognized OpenGL version!" << endl;
		exit(1);
	}

	cout << "OpenGL version: "  << glGetString(GL_VERSION) << endl;
	cout << "OpenGL vendor: "   << glGetString(GL_VENDOR) << endl;
	cout << "OpenGL renderer: " << glGetString(GL_RENDERER) << endl;

	cout << "OpenGL doubleBuffer: "      <<  doubleBuffer() << endl;
	cout << "OpenGL texturecachelimit: " <<  context()->textureCacheLimit() << " kB" << endl; 
	cout << "OpenGL framebuffer objects: " << QGLFramebufferObject::hasOpenGLFramebufferObjects() << endl;
	cout << "OpenGL overlay: " 	   << format().hasOpenGLOverlays() << endl;
	cout << "OpenGL directRendering: " << format().directRendering() << endl;
	cout << "OpenGL red:   " <<  format().redBufferSize() << " bits" << endl;
	cout << "OpenGL green: " <<  format().greenBufferSize() << " bits" << endl;
	cout << "OpenGL blue:  " <<  format().blueBufferSize() << " bits" << endl;
	cout << "OpenGL alha:  " <<  format().alphaBufferSize() << " bits" << endl;

	/*GLint ival[0];
	glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS_EXT,ival);

	cout << "OpenGL fbo color attachments: "  <<  ival[0] << endl;

	glGetIntegerv(GL_MAX_RENDERBUFFER_SIZE_EXT,ival);
	cout << "OpenGL max renderbuffer size: "  <<  ival[0] << endl;


	const GLubyte* extstr=glGetString(GL_EXTENSIONS);	
	cout << "Available OpenGL extensions:" << endl << extstr << endl;*/	
	
	/*if(gluCheckExtension(reinterpret_cast<const GLubyte*>("GL_EXT_framebuffer_object")
	                     ,extstr) == GL_TRUE)
	{
	    cout << "Extension: GL_EXT_framebuffer_object found!!!"  << endl; 
	}*/

	//glClearColor(1.0, 1.0, 1.0, 1.0);
	//glClear(GL_COLOR_BUFFER_BIT);
}

void GLWidget::resizeGL(int w, int h)
{
	//We suppose we are in MODELVIEW mode
	/*glMatrixMode(GL_MODELVIEW);

	glViewport(0,0,w/2,h/2);

	GLdouble modelMatrix[16],projMatrix[16];
	GLint viewport[4];
	GLdouble rx_min,ry_min,rx_max,ry_max,rz;

        glGetDoublev(GL_MODELVIEW_MATRIX,modelMatrix);
	glGetDoublev(GL_PROJECTION_MATRIX,projMatrix);
	glGetIntegerv(GL_VIEWPORT,viewport);*/				
}

void GLWidget::paintGL()
{
	cout << "paintGL" << endl;
	//GLint ival[0];
	//glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS_EXT,ival);

	//cout << "OpenGL fbo color attachments: "  <<  ival[0] << endl;

	//glGetIntegerv(GL_MAX_RENDERBUFFER_SIZE_EXT,ival);
	//cout << "OpenGL max renderbuffer size: "  <<  ival[0] << endl;


	//const GLubyte* extstr=glGetString(GL_EXTENSIONS);	
	//cout << "Available OpenGL extensions:" << endl << extstr << endl;	

	MagPlusService::Instance().restoreFb();
	swapBuffers();
}

void GLWidget::mousePressEvent(QMouseEvent* event)
{
	MtMouseEvent gle;

	gle.setType(Mt::MousePressEvent);
	gle.setX(event->x());
	gle.setY(height()-event->y());
	if(event->button() & Qt::LeftButton)
	{
		gle.setButton(Mt::LeftButton);
	}
	if(event->button() & Qt::MidButton)
	{
		gle.setButton(Mt::MidButton);
	}
	if(event->button() & Qt::RightButton)
	{
		gle.setButton(Mt::RightButton);
	}
	
//	cout << "mousePress: " << event->x() << " "  << event->y() <<  endl;
	MagPlusService::Instance().InputEvent(&gle);
}

void GLWidget::mouseMoveEvent (QMouseEvent* event)
{
	MtMouseEvent gle;

	gle.setType(Mt::MouseMoveEvent);
	gle.setX(event->x());
	gle.setY(height()-event->y());
	if(event->buttons().testFlag(Qt::LeftButton))
	{
		gle.setButton(Mt::LeftButton);
	}
	if(event->buttons().testFlag(Qt::MidButton))
	{
		gle.setButton(Mt::MidButton);
	}
	if(event->buttons().testFlag(Qt::RightButton))
	{
		gle.setButton(Mt::RightButton);
	}

//	cout << "mouseMove: " << event->x() << " "  << event->y() <<  endl;
	MagPlusService::Instance().InputEvent(&gle);
}

void GLWidget::mouseReleaseEvent (QMouseEvent* event)
{
	MtMouseEvent gle;

	gle.setType(Mt::MouseReleaseEvent);
	gle.setX(event->x());
	gle.setY(height()-event->y());
	if(event->button() & Qt::LeftButton)
	{
		gle.setButton(Mt::LeftButton);
	}
	if(event->button() & Qt::MidButton)
	{
		gle.setButton(Mt::MidButton);
	}
	if(event->button() & Qt::RightButton)
	{
		gle.setButton(Mt::RightButton);
	}

//	cout << "mouseRelease: " << event->x() << " "  << event->y() <<  endl;
	MagPlusService::Instance().InputEvent(&gle);
}

void GLWidget::keyPressEvent(QKeyEvent* event)
{
	MtKeyEvent gle;
	
        Mt::Key key=getMtKey(event->key());
	if(key != Mt::Key_Unknown)
	{
		MtKeyEvent gle;
		gle.setType(Mt::KeyPressEvent);	
		gle.setKey(key);
		gle.setText(event->text().toStdString());

		MagPlusService::Instance().InputEvent(&gle);
	}
	else
	{
		QGLWidget::keyPressEvent(event);
	}
}

void GLWidget::keyReleaseEvent(QKeyEvent* event)
{
	QGLWidget::keyReleaseEvent(event);
}

void GLWidget::setCursor(const string& cursorName)
{
	QWidget::setCursor(QCursor(getQtCursorShape(cursorName)));
}

/*void GLWidget::paintEvent(QPaintEvent *event) 
{
	
	cout << "paintEvent" << endl;
	
	glMatrixMode(GL_MODELVIEW);
     	glPushMatrix();
	glLoadIdentity();
	glPushAttrib(GL_COLOR_BUFFER_BIT | GL_POLYGON_BIT | GL_VIEWPORT_BIT);

 	QPainter painter(this);

	MagPlusService::Instance().restoreFb();

	glPolygonMode(GL_FRONT,GL_FILL);

	painter.fillRect(QRect(0, 0, 300, 300),
                      QColor(220, 0, 0, 127));
        painter.end();

	glPopMatrix();
	
	glPopAttrib();

	swapBuffers();
}*/
