#include "QFitsDisplay.h"
#include <qapplication.h>
#include <qmessagebox.h>
#include <qpainter.h>

QFitsDisplay::QFitsDisplay(QWidget *parent)
: QWidget(parent) {
	data = new Fits();
	data->create(0, 0);
	image.newFits(data);
	setUpdatesEnabled(FALSE);
}

bool QFitsDisplay::LoadFile(QString &fname) {
	QApplication::setOverrideCursor(waitCursor);
	if (data->ReadFITS((char *)fname.latin1())) {
		QApplication::restoreOverrideCursor();
	} else {
		QImage newimage;
		if (!newimage.load(fname)) {
			QApplication::restoreOverrideCursor();
			QApplication::beep();
			QMessageBox::critical(0, "FitsView", QString(fname) + " is not a valid image");
			return FALSE;
		} else {
			int x, y, n = 0;

			data->create(newimage.height(), newimage.width(), I1);
			for (x = 0; x < newimage.width(); x++) {
				for (y = 0; y < newimage.height(); y++) {
					data->i1data[n++] = qGray(newimage.pixel(x, y));
				}
			}
			data->rot90(90);
//			ScaleImage(0.0, 0.0);
			QApplication::restoreOverrideCursor();
		}
	}
	QWidget *p = (QWidget *)parent()->parent()->parent();
	p->setCaption(QString("QFitsView by Thomas Ott - ") + fname);
	image.newFits(data);
//	resize(image.width(), image.height());
//	enableMovie(FALSE);
//	emit newCube(data.Naxis(3));
	return TRUE;
}

void QFitsDisplay::paintEvent( QPaintEvent * )
{
	QPixmap pm;

	if ((image.width() != width()) || (image.height() != height())) resize(image.width(), image.height());
	pm = image;
	bitBlt(this, width()/2-pm.width()/2, height()/2-pm.height()/2, &pm, 0, 0, pm.width(), pm.height(), CopyROP, TRUE);
}

void QFitsDisplay::resizeEvent( QResizeEvent *e )
{
	int x, y;

	move(0, 0);
	x = (parentWidget()->width() - width()) / 2;
	y = (parentWidget()->height() - height()) / 2;
	if (x < 0) x = 0;
	if (y < 0) y = 0;
	if ((x > 0) || (y > 0))
		move(x, y);
	else
		move(0, 0);
//	repaint(FALSE);
}

