/***************************** 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 std::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 std::string& cursorName)
{
    static std::map<std::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()
{
    std::cout << "initializeGL" << std::endl;

    setAutoBufferSwap(false);

    const char* version = (const char*)glGetString(GL_VERSION);

    if (version == 0) {
        std::cout << "Unrecognized OpenGL version!" << std::endl;
        exit(1);
    }

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

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

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

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

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


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

    /*if(gluCheckExtension(reinterpret_cast<const GLubyte*>("GL_EXT_framebuffer_object")
	                     ,extstr) == GL_TRUE)
	{
	    std::cout << "Extension: GL_EXT_framebuffer_object found!!!"  << std::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()
{
    std::cout << "paintGL" << std::endl;
    //GLint ival[0];
    //glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS_EXT,ival);

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

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


    //const GLubyte* extstr=glGetString(GL_EXTENSIONS);
    //std::cout << "Available OpenGL extensions:" << std::endl << extstr << std::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);
    }

    //	std::cout << "mousePress: " << event->x() << " "  << event->y() <<  std::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);
    }

    //	std::cout << "mouseMove: " << event->x() << " "  << event->y() <<  std::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);
    }

    //	std::cout << "mouseRelease: " << event->x() << " "  << event->y() <<  std::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 std::string& cursorName)
{
    QWidget::setCursor(QCursor(getQtCursorShape(cursorName)));
}

/*void GLWidget::paintEvent(QPaintEvent *event) 
{
	
	std::cout << "paintEvent" << std::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();
}*/
