#include <QtGui/QMouseEvent>
#include "videoWidget.hh"

using namespace mimas;

VideoWidget::VideoWidget( QWidget *parent, Qt::WFlags ):
  QGLWidget( parent ), offsetX(0), offsetY(0), zoom(1.0)
{
}

void VideoWidget::setImage( const image< rgba< unsigned char > > &_img ) 
{
  setImage( 0,0, _img.getWidth(), _img.getHeight(), _img );
}

void VideoWidget::setImage( int _offsetX, int _offsetY,
                            int _width, int _height,
                            const image< rgba< unsigned char > > &_img )
{
  offsetX = _offsetX;
  offsetY = _offsetY;
  img = _img;
  adaptSize( _width, _height );
  update();
}

void VideoWidget::wheelEvent( QWheelEvent *e )
{
  zoom += e->delta() / 1200.0;
  if ( zoom < 0.1 ) zoom = 0.1;
  if ( zoom > 2.5 ) zoom = 2.5;
  adaptSize( img.getWidth(), img.getHeight() );
  update();
}

void VideoWidget::initializeGL(void)
{
  qglClearColor( QColor( 32, 32, 32 ) );
}

void VideoWidget::resizeGL( int w, int h )
{
  glViewport( 0, 0, (GLint)w, (GLint)h );
  glMatrixMode( GL_PROJECTION );
  glLoadIdentity();
  glOrtho( 0, width(), height(), 0, -1, 1 );
  glMatrixMode( GL_MODELVIEW );
}

void VideoWidget::paintGL(void)
{
  glClear( GL_COLOR_BUFFER_BIT );
  if ( img.initialised() ) {
    glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );
    // glPixelStorei( GL_UNPACK_ROW_LENGTH, 0 );
    // glPixelStorei( GL_UNPACK_SKIP_PIXELS, 0 );
    // glPixelStorei( GL_UNPACK_SKIP_ROWS, 0 );
    glRasterPos2f( offsetX * zoom, offsetY * zoom );
    glPixelZoom( zoom, -zoom );
    // Direct access to image-memory!
    glDrawPixels( img.getWidth(), img.getHeight(),
                  GL_BGRA, GL_UNSIGNED_BYTE, img.rawData() );
  };
};

void VideoWidget::adaptSize( int w, int h )
{
  int
    newW = (int)( w * zoom ),
    newH = (int)( h * zoom );
  if ( width() != newW || height() != newH ) {
    resize( newW, newH );
  };
}