#include "magnifierwidget.h"

#include <QPainter>

MagnifierWidget::MagnifierWidget(QWidget *parent) : QWidget(parent)
{
    this->loupeScale = 3.0;
    this->zoomRegionCenterX = 20;
    this->zoomRegionCenterY = 20;
    this->widgetWidth = 120;
    this->widgetHeight = 120;
    this->setGeometry(2, 2, 122, 122);
}

MagnifierWidget::MagnifierWidget(int w, int h, QWidget *parent) : QWidget(parent)
{
    this->loupeScale = 3.0;
    this->zoomRegionCenterX = 20;
    this->zoomRegionCenterY = 20;
    //this->setFixedSize(w, h);
    this->widgetWidth = w;
    this->widgetHeight = h;
    this->setGeometry(2, 2, w + 2, h + 2);
}

void MagnifierWidget::setZoomRegionCenter(int x, int y)
{
    this->zoomRegionCenterX = x;
    this->zoomRegionCenterY = y;
}

void MagnifierWidget::setLoupeScale(float value)
{
    this->loupeScale = value;
}

void MagnifierWidget::setLoupePixmap(QPixmap pix)
{
    srcPixmap = pix.copy(0, 0, pix.width(), pix.height());
}

void MagnifierWidget::paintEvent(QPaintEvent *)
{
    QPainter painter;
    if(painter.begin(this))
    {
        painter.setRenderHints(QPainter::Antialiasing, true);

        int cpyWidth = widgetWidth / loupeScale;
        int cpyHeight = widgetWidth / loupeScale;

        if(zoomRegionCenterX < cpyWidth/2)
            zoomRegionCenterX = cpyWidth/2;
        if(zoomRegionCenterY < cpyHeight/2)
            zoomRegionCenterY = cpyHeight/2;
        if(zoomRegionCenterX > srcPixmap.width() - cpyWidth/2)
            zoomRegionCenterX = srcPixmap.width() - cpyWidth/2;
        if(zoomRegionCenterY > srcPixmap.height() - cpyHeight/2)
            zoomRegionCenterY = srcPixmap.height() - cpyHeight/2;


        QTransform tr;
        tr.translate(0, 0);
        tr.scale(loupeScale, loupeScale);
        scaledRoiPixmap = srcPixmap.copy(zoomRegionCenterX - cpyWidth/2, zoomRegionCenterY - cpyHeight/2, cpyWidth, cpyHeight);
        QBrush brush(scaledRoiPixmap);
        brush.setTransform(tr);
        painter.setBrush(brush);
        painter.drawEllipse(0, 0, widgetWidth, widgetHeight);

        //draw the frame
        painter.setPen(QPen(QColor(160,160,160), 1));
        painter.drawEllipse(-1, -1, widgetWidth+2, widgetHeight+2);
        painter.setPen(QPen(QColor(255,255,255), 2));
        painter.drawEllipse(0, 0, widgetWidth, widgetHeight);
        painter.setPen(QPen(QColor(215,215,215), 1));
        painter.drawEllipse(1, 1, widgetWidth-2, widgetHeight-2);

        //draw a cross
        painter.setPen(QPen(Qt::green, 1));
        painter.drawLine(QPointF(widgetWidth/2 - 8, widgetHeight/2), QPointF(widgetWidth/2 + 8, widgetHeight/2));
        painter.drawLine(QPointF(widgetWidth/2, widgetHeight/2 - 8), QPointF(widgetWidth/2, widgetHeight/2 + 8));

        painter.end();
    }
}
