#include "ImageCanvas.h"
#include <QDebug>

using namespace std;
using namespace mvIMPACT::acquire;

//=============================================================================
//================= Implementation ImageCanvasImpl ============================
//=============================================================================
//-----------------------------------------------------------------------------
struct ImageCanvasImpl
//-----------------------------------------------------------------------------
{
    QLabel* pLabel_;
    QImage image_;

    ImageCanvasImpl( QLabel* pLabel ): pLabel_( pLabel ) {}
};

//=============================================================================
//================= Implementation ImageCanvas ================================
//=============================================================================
//-----------------------------------------------------------------------------
ImageCanvas::ImageCanvas( QLabel* pLabel )
//-----------------------------------------------------------------------------
{
    pImpl_ = new ImageCanvasImpl( pLabel );
    pImpl_->pLabel_->setAlignment( Qt::AlignHCenter );
}

//-----------------------------------------------------------------------------
void ImageCanvas::SetImage( Request* pRequest )
//-----------------------------------------------------------------------------
{
    if( pRequest && pRequest->getNumber() != INVALID_ID )
    {
        QImage::Format iQtImageFormat = QImage::Format_Invalid;
        switch( pRequest->imagePixelFormat.read() )
        {
        case ibpfMono8:
            iQtImageFormat = QImage::Format_Grayscale8;
            break;
        case ibpfRGBx888Packed:
            iQtImageFormat = QImage::Format_RGB32;
            break;
        case ibpfBGR888Packed:
        case ibpfRGB888Packed:
            iQtImageFormat = QImage::Format_RGB888;
            break;
        default:
            pImpl_->pLabel_->setText( "PIXEL FORMAT NOT SUPPORTED BY THE DISPLAY\nPlease use RGB888, RGBx888, BGR888 or Mono8 instead!" );
            break;
        }

        if( iQtImageFormat != QImage::Format_Invalid )
        {
            pImpl_->image_ = QImage( static_cast<uchar*>( pRequest->imageData.read() ), pRequest->imageWidth.read(), pRequest->imageHeight.read(), pRequest->imageLinePitch.read(), iQtImageFormat );
            if( pRequest->imagePixelFormat.read() == ibpfRGB888Packed )
            {
                pImpl_->image_ = pImpl_->image_.rgbSwapped(); // For historical reasons RGB in mvIMPACT Acquire is BGR...
            }
            pImpl_->pLabel_->setPixmap( QPixmap::fromImage( pImpl_->image_ ).scaled( pImpl_->pLabel_->width(), pImpl_->pLabel_->height(), Qt::IgnoreAspectRatio ) );
        }

        pRequest->unlock();
        // this approach only works once no repaint of the GUI is triggered!
    }
}
