#include "qimagecontrol.h"
#include <algorithm>
#include <iostream.h>
using namespace std;

#include <qapp.h>
#include <qimage.h>
#include <qpainter.h>
#include <qpixmap.h>

namespace
{
    const QEvent::Type Type_LeftPix=QEvent::Type(QEvent::User);
    const QEvent::Type Type_RightPix=QEvent::Type(QEvent::User+1);
};
QImageControl::QImageControl(QWidget* parent, const char* name):QWidget(parent,name),_il(0), _ir(0)
{
    _left=new QFrame(this);
    _right=new QFrame(this);
    _left->setFrameShadow( QFrame::Sunken );
    _left->setFrameShape( QFrame::Box );
    _right->setFrameShadow( QFrame::Sunken );
    _right->setFrameShape( QFrame::Box );
    _w=_h=0;
    _il=_ir=0;
    setSize(192,144);
    pthread_mutex_init(&mutex, 0);
}

QImageControl::~QImageControl()
{
    pthread_mutex_destroy(&mutex);
    if (_il)
	_il->Release();
    if (_ir)
	_ir->Release();
}

void QImageControl::setSize(int width, int height)
{
    if (height<0)
	height=-height;
    _left->resize(width, height);
    _right->resize(width, height);

    int nw = width + 10;
    int nh = 5;

    if (height < 400)
    {
	nw = 5;
        nh = height + 10;
    }
    _left->move(5, 5);
    _right->move(nw, nh);
    _w=width;
    _h=height;
    resize(width + 5 + nw, height + 5 + nh);
}
void QImageControl::setSourcePicture(const CImage* src)
{
    pthread_mutex_lock(&mutex);
    if (_il)
	_il->Release();
    _il = new CImage(src, 32);
    pthread_mutex_unlock(&mutex);
    QEvent* e = new QEvent(Type_LeftPix);
    qApp->postEvent(this, e);
    //qApp->sendPostedEvents();
}

void QImageControl::setDestPicture(const CImage* src)
{
    pthread_mutex_lock(&mutex);
    if (_ir)
	_ir->Release();
    _ir = new CImage(src, 32);
    pthread_mutex_unlock(&mutex);
    QEvent* e = new QEvent(Type_RightPix);
    qApp->postEvent(this, e);
}

void QImageControl::setPicture(const CImage* im, QFrame* frame)
{
    if (!im)
	return;

    int bitdepth = 32;
    _w = im->Width();
    _h = im->Height();
    int bpl=_w*4;
    QImage* i=new QImage(_w, _h, 32);
    int y;
    if (im->Data() == 0)
	abort();

    if (!im->Direction())
	for(y=0;y<_h;y++)
	{
	    QRgb *line = (QRgb *)i->scanLine(y);
	    memcpy(line,im->At(y),bpl);
	}
    else
	for(y=0;y<_h;y++)
	{
	    QRgb *line = (QRgb *)i->scanLine(y);
	    memcpy(line,im->At(_h-1-y),bpl);
	}
    QPainter p(frame);
    p.drawImage(0,0,*i);
    delete i;
}

void QImageControl::paintEvent(QPaintEvent*)
{
    pthread_mutex_lock(&mutex);
    setPicture(_il, _left);
    setPicture(_ir, _right);
    pthread_mutex_unlock(&mutex);
}

bool QImageControl::event(QEvent* ev)
{
    if (ev->type()==Type_LeftPix)
    {
	pthread_mutex_lock(&mutex);
	setPicture(_il, _left);
	pthread_mutex_unlock(&mutex);
	return true;
    }
    else if (ev->type()==Type_RightPix)
    {
	pthread_mutex_lock(&mutex);
    	setPicture(_ir, _right);
	pthread_mutex_unlock(&mutex);
	return true;
    }

    return QWidget::event(ev);
}
