#include "ivgraphicsview.h"

IvGraphicsView::IvGraphicsView(QGraphicsScene *scene,
                               QWidget *parent) : QGraphicsView(parent)
{
    this->setParent(parent);
    this->setScene(scene);

    this->setDragMode(QGraphicsView::ScrollHandDrag);
    this->setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
    this->setResizeAnchor(QGraphicsView::AnchorUnderMouse);

    qDebug() << "IvGraphicsView created";
}

IvGraphicsView::~IvGraphicsView()
{
    qDebug() << "IvGraphicsView destroyed";
}

/*
 * Calculate scale factor (or zoom level), to scale like fitInView()
 *
 */
double IvGraphicsView::getScaleToFit(int width, int height, int angle)
{
    double scaleLevel;

    double imageWidth = qMax(width, 1);
    double imageHeight = qMax(height, 1);
    if (qAbs(angle) == 90 || qAbs(angle) == 270) // Partially turned to either side
    {
        qSwap(imageWidth, imageHeight);
    }

    double viewportWidth = qMax(this->viewport()->width(), 1);
    double viewportHeight = qMax(this->viewport()->height(), 1);

    double imageRatio = imageWidth / imageHeight;
    double viewportRatio = viewportWidth / viewportHeight;

    if (imageRatio > viewportRatio)
    {
        scaleLevel = viewportWidth / imageWidth;
    }
    else
    {
        scaleLevel = viewportHeight / imageHeight;
    }

    // TODO: round scaleLevel to .00/.05/.10

    return qBound(0.05, scaleLevel, 5.0);
}


//////////////////////////////////////////////////////////////////////////////
/////////////////////////////////// PROTECTED ////////////////////////////////
//////////////////////////////////////////////////////////////////////////////


void IvGraphicsView::wheelEvent(QWheelEvent *event)
{
    // Only for vertical axis changes
    if (event->angleDelta().y() != 0)
    {
        emit zoomableModeRequested();

        if (event->angleDelta().y() > 0)
        {
            emit zoomInRequested();
        }
        else
        {
            emit zoomOutRequested();
        }

        event->accept();
    }
}


void IvGraphicsView::mouseDoubleClickEvent(QMouseEvent *event)
{
    emit doubleClicked();

    event->accept();
}
