#include <QPainter>

#include "QFitsWedge.h"
#include "QFitsMainView.h"
#include "QFitsMainWindow.h"
#include "QFitsSingleBuffer.h"

QFitsWedge::QFitsWedge(QFitsMainView *parent) : QWidget(parent), myParent(parent) {
    image = new QImage(1, 1, QImage::Format_Indexed8);
    image->setColorCount(NCOLORS);
    setMinimumHeight(10);
    setMaximumHeight(10);
}

void QFitsWedge::paintEvent(QPaintEvent *e) {
    if ((fitsMainWindow->getCurrentBuffer() == NULL) ||
        fitsMainWindow->getCurrentBuffer()->getAppearance().hideWedge)
    {
        return;
    }

    QFitsSingleBuffer *sb = fitsMainWindow->getActualSB();
    if (sb != NULL) {
        QImage *sbImg = sb->getImage();
        for (int i = 0; i < NCOLORS; i++) {
            image->setColor(i, sbImg->color(i));
        }

        QPixmap pm(width(), height());
        QPainter p;
        p.begin(&pm);
        p.drawImage(0, 0, *image);
        p.end();

        QPainter painter(this);
        painter.drawPixmap(width()/2-pm.width()/2,
                           height()/2-pm.height()/2,
                           pm, 0, 0,
                           pm.width(), pm.height());
    }
}

void QFitsWedge::resizeEvent(QResizeEvent *e) {
    if (image != NULL) {
        delete image;
    }
    image = new QImage(width(), height(), QImage::Format_Indexed8);
    image->setColorCount(NCOLORS);

    for (int y = 0; y < image->height(); y++) { // set image pixels
        uchar *p = image->scanLine(y);
        for (int x = 0; x < image->width(); x++) {
            *p++ = (unsigned char)((image->width() - x) * (NCOLORS-1) / image->width());
        }
    }
    for (int i = 0; i < NCOLORS; i++) {
        image->setColor(i, colourTable[i]);
    }
    update();
}
