#include "imagerenderglwidget.h"
#include "clientglobals.h"
#include "connectionprofiler.h"
#include "clientsocket.h"

#include <QGLFramebufferObject>
#include <QPainter>
#include <QPaintEvent>
#include <QResizeEvent>
#include <QCursor>
#include <QApplication>
#include <QGLFormat>
#include <QTime>
#include <QTimer>
#include <QDebug>

#ifndef GL_TEXTURE_RECTANGLE_EXT
#define GL_TEXTURE_RECTANGLE_EXT GL_TEXTURE_RECTANGLE_NV
#endif

void ImageRenderGLWidget::initFramebuffer( const QSize &size )
{
    makeCurrent();
    m_rfb = new QGLFramebufferObject(size);
    QPainter p( m_rfb );
    p.fillRect(0,0,size.width(),size.height(), Qt::black );
    p.end();
}

ImageRenderGLWidget::ImageRenderGLWidget(QWidget *parent ) :
        QGLWidget( QGLFormat(QGL::SampleBuffers|QGL::AlphaChannel), parent ),
        m_x(0),
        m_y(0),
        m_width(0),
        m_height(0)
{
    setFocusPolicy ( Qt::StrongFocus );
    setMouseTracking( true );
    initFramebuffer(size());
}

ImageRenderGLWidget::~ImageRenderGLWidget()
{
    makeCurrent();
    delete m_rfb;
}

void ImageRenderGLWidget::handleFramebufferResize( const QSize &size )
{
    makeCurrent();
    delete m_rfb;
    initFramebuffer(size);
}

void ImageRenderGLWidget::mergeFramebufferChange( const QRect &area, const QImage &img )
{
    makeCurrent();
    QPainter p( m_rfb );
    p.setCompositionMode(QPainter::CompositionMode_Source);
    p.drawImage( area, img);
    p.end();
}

void ImageRenderGLWidget::initializeGL()
{
    qglClearColor(Qt::black);
    glEnable(GL_TEXTURE_2D);
}

void ImageRenderGLWidget::paintGL()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    drawTexture(QRect(m_x,m_y,m_width,m_height), m_rfb->texture());
}

void ImageRenderGLWidget::resizeGL(int width, int height)
{
    double this_aspect = (double) width / height;
    double display_ratio = 4.0 / 3.0;

    // Special case optimisation to negate odd effect of sample aspect ratio
    // not corresponding exactly with image resolution.
    if ((int)(this_aspect * 1000) == (int)(display_ratio * 1000))
    {
        m_width = width;
        m_height = height;
    }
    // Use OpenGL to normalise sample aspect ratio
    else if (height * display_ratio > width)
    {
        m_width = width;
        m_height = width / display_ratio;
    }
    else
    {
        m_width = height * display_ratio;
        m_height = height;
    }

    m_x = (width - m_width) / 2;
    m_y = (height - m_height) / 2;

    glViewport(0, 0, m_width, m_height);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0, m_width, m_height, 0);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}

