#include "calibrateWidget.hh"

using namespace std;
using namespace mimas;

CalibrateWidget::CalibrateWidget( QWidget *parent, Qt::WFlags f ):
  QGLWidget( parent, 0, f ), pattern(0)
{
}

CalibrateWidget::CalibrateWidget
  ( const image< unsigned char > &_projectedPattern,
    QWidget *parent, Qt::WFlags f ):
  QGLWidget( parent ), projectedPattern( _projectedPattern ),
  pattern(0)
{
}

void CalibrateWidget::initializeGL(void)
{
  qglClearColor( Qt::black );
}

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

void CalibrateWidget::paintGL(void)
{
  glClear( GL_COLOR_BUFFER_BIT );
  glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );
  if ( projectedPattern.initialised() && pattern >= 1 && pattern <= 5 ) {
    glPixelZoom( 1, -1 );
    Vector pos( getPos( pattern ) );
    glRasterPos2d( pos[0] - projectedPattern.getWidth() / 2,
                   pos[1] - projectedPattern.getHeight() / 2 );
    glDrawPixels( projectedPattern.getWidth(), projectedPattern.getHeight(),
                  GL_LUMINANCE, GL_UNSIGNED_BYTE,
                  projectedPattern.rawData() );
  };
};

CalibrateWidget::Vector CalibrateWidget::getPos( int i )
{
  assert( projectedPattern.initialised() );
  assert( pattern >= 1 && pattern <= 5 );
  int
    xmax = width() - projectedPattern.getWidth(),
    ymax = height() - projectedPattern.getHeight(),
    x,
    y;
  switch ( pattern ) {
  case 1:
    x = 0;
    y = 0;
    break;
  case 2:
    x = xmax;
    y = 0;
    break;
  case 3:
    x = 0;
    y = ymax;
    break;
  case 4:
    x = xmax;
    y = ymax;
    break;
  default:
    x = xmax / 2;
    y = ymax / 2;
  };
  Vector retVal( 3 );
  retVal[ 0 ] = x + projectedPattern.getWidth()  / 2;
  retVal[ 1 ] = y + projectedPattern.getHeight() / 2;
  retVal[ 2 ] = 1.0;
  return retVal;
}

void CalibrateWidget::setPattern( int _pattern )
{
  if ( pattern != _pattern ) {
    pattern = _pattern;
    update();
  };
}