/***************************** LICENSE START ***********************************

 Copyright 2012 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#include <QDebug>
#include <QMouseEvent>
#include <QPainter>

#include "MvQZoom.h"
#include "MvQPlotView.h"
#include "MgQPlotScene.h"
#include "MgQLayoutItem.h"
#include "MgQSceneItem.h"

MvQZoom::MvQZoom(MgQPlotScene* scene, MvQPlotView* view, QGraphicsItem* parent) :
    MvQPlotItem(scene, view, parent)
{
    pen_ = QPen(QColor(110, 110, 110), 2);
    brush_ = QBrush(QColor(230, 230, 230, 180));
    currentAction_ = NoAction;
    zoomLayout_ = nullptr;
    zoomWasPerformedAfterMouseRelease_ = false;
}

MvQZoom::~MvQZoom() = default;

QRectF MvQZoom::boundingRect() const
{
    // return zoomRect_.adjusted(-2,-2,2,-2);
    return zoomRect_;
}

void MvQZoom::paint(QPainter* painter, const QStyleOptionGraphicsItem*, QWidget*)
{
    //	qDebug() << "zoom" << zoomRect_;

    painter->setPen(QPen());
    painter->setBrush(brush_);
    painter->drawRect(zoomRect_);

    painter->setPen(pen_);
    painter->setBrush(QBrush());
    painter->drawRect(zoomRect_);
}

void MvQZoom::mousePressEventFromView(QMouseEvent* event)
{
    if (activated_ && acceptMouseEvents_ &&
        event->buttons() & Qt::LeftButton) {
        // Get scene position
        zoomRectOrigin_ = plotView_->mapToScene(event->pos());

        MgQSceneItem* sceneItem = nullptr;

        if (plotScene_->identifyPos(zoomRectOrigin_, &sceneItem, &zoomLayout_)) {
            currentAction_ = ZoomAction;

            // Set geometry
            zoomRect_.setRect(zoomRectOrigin_.x(), zoomRectOrigin_.y(), 0, 0);

            setVisible(true);

            emit mousePressInSceneItem(sceneItem);
        }
        else {
            currentAction_ = NoAction;
        }
    }
}

void MvQZoom::mouseMoveEventFromView(QMouseEvent* event)
{
    if (activated_ && acceptMouseEvents_ &&
        currentAction_ == ZoomAction) {
        QPointF pos = plotView_->mapToScene(event->pos());
        QPointF dp = pos - zoomRectOrigin_;

        if (dp.x() <= 0. || dp.y() >= 0.)
            return;

        if (!zoomLayout_->contains(zoomLayout_->mapFromScene(pos)))
            return;

        prepareGeometryChange();
        // zoomRect_=QRectF(zoomRectOrigin_, pos);
        zoomRect_ = QRectF(zoomRectOrigin_.x(), pos.y(), dp.x(), -dp.y());

        //		qDebug() << "zoom update" << isVisible() << boundingRect();

        update();
    }
}

void MvQZoom::mouseReleaseEventFromView(QMouseEvent* event)
{
    if (activated_ && acceptMouseEvents_ &&
        currentAction_ == ZoomAction) {
        QPointF pos = plotView_->mapToScene(event->pos());
        QPointF dp = pos - zoomRectOrigin_;

        // Rubberband rect in scene coordinates
        // QRectF rect(zoomRectOrigin_,pos);
        QRectF rect(zoomRectOrigin_.x(), pos.y(), dp.x(), -dp.y());

        if (dp.x() <= 0. || dp.y() >= 0. || fabs(rect.width()) <= 8. || fabs(rect.height()) <= 8.) {
            setVisible(false);

            // plotScene_->removeItem(rubberBand_);

            // Reset zoom data
            currentAction_ = NoAction;
            zoomWasPerformedAfterMouseRelease_ = false;
            zoomLayout_ = nullptr;
        }
        else {
            // Get geo coordinates of rect corners
            QPointF sp1 = zoomRect_.topLeft();
            QPointF sp2 = zoomRect_.bottomRight();
            // zoomLayout_->mapFromSceneToGeoCoords(sp1,gp1);
            // zoomLayout_->mapFromSceneToGeoCoords(sp2,gp2);

            std::string trDef = zoomLayout_->mapFromSceneToTransformationDefinition(sp1, sp2);

            QString layoutId(zoomLayout_->layout().id().c_str());
            setVisible(false);

            // Reset zoom data
            currentAction_ = NoAction;
            zoomWasPerformedAfterMouseRelease_ = true;
            zoomLayout_ = nullptr;

            //			qDebug() << "zoom def:" << QString(trDef.c_str());

            // Perform the zoom
            emit zoomRectangleIsDefined(layoutId.toStdString(), trDef);
        }
    }
    else {
        zoomWasPerformedAfterMouseRelease_ = false;
    }
}
