#include <QWidget>
#include <QMouseEvent>
#include <QScrollBar>

#include "QFitsMainView.h"
#include "QFitsSingleBuffer.h"

#include "QFitsScroller.h"
#include "QFitsWidget2D.h"
#include "fits.h"

QFitsScroller::QFitsScroller(QWidget *parent)
                            : QScrollArea(parent), myParent(parent)
{
    setWidgetResizable(true);
    sliderActive = false;

    connect(horizontalScrollBar(), SIGNAL(sliderPressed()),
            this, SLOT(sliderActivated()));
    connect(horizontalScrollBar(), SIGNAL(sliderReleased()),
            this, SLOT(sliderDeactivated()));
    connect(verticalScrollBar(), SIGNAL(sliderPressed()),
            this, SLOT(sliderActivated()));
    connect(verticalScrollBar(), SIGNAL(sliderReleased()),
            this, SLOT(sliderDeactivated()));
}

void QFitsScroller::calculateScaling(Fits *fits) {
    QFitsWidget2D *widget2D = dynamic_cast<QFitsWidget2D*>(myParent);
    if (widget2D != NULL) {
        widget2D->calculateScaling(fits);
    }
}

void QFitsScroller::viewportMouseMoveEvent(QMouseEvent *m) {
    if (m->button() == Qt::LeftButton) {
        processMouseClick(m->x(), m->y());
    }
}

void QFitsScroller::processMouseClick(int x, int y) {
    QFitsWidget2D *widget2D = dynamic_cast<QFitsWidget2D*>(myParent);
    if (widget2D != NULL) {
        widget2D->getMyBuffer()->setBrightnessContrast(
                                    (int)((float)x / (float)width() * 1000.),
                                    (int)((float)y / (float)height() * 1000.));
    }
}

void QFitsScroller::sliderActivated() {
    sliderActive = true;
}

void QFitsScroller::sliderDeactivated() {
    sliderActive = false;
}
