/***************************** 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 "GeoTool.h"
#include "ObjectList.h"
#include "PlotMod.h"
#include "Preferences.h"

#include <QAction>
#include <QApplication>
#include <QChar>
#include <QDebug>
#include <QLabel>
#include <QPushButton>
#include <QAction>
#include <QStringBuilder>
#include <QStyle>
#include <QToolBar>
#include <QVBoxLayout>

#include "MgQPlotScene.h"
#include "MgQSceneItem.h"

#include "MvQApplication.h"
#include "MvQPlotView.h"
#include "MvQZoomStackWidget.h"
#include "MvQMethods.h"
#include "MvLog.h"

GeoTool::GeoTool(MvRequest& req, QWidget* parent) :
    uPlotBase(parent)
{
    // Initialize variables
    QString coord = InitializeParams(req);
    setAttribute(Qt::WA_DeleteOnClose);
    setWindowTitle("Metview - Geography Tool");

    //Initial size
    setInitialSize(600, 400);

    //uPlot area. Define the whole lot as central widget
    auto* w = new QWidget;
    setCentralWidget(w);
    auto* vlay = new QVBoxLayout(w);
    vlay->addWidget(plotView_);

    //Setup the bottom layout (coordinates + buttons)
    auto* hlay = new QHBoxLayout();
    vlay->addLayout(hlay);
    auto* coordLabel = new QLabel(tr("S/W/N/E:"));
    coordEdit_       = new QLineEdit();
    coordEdit_->setMinimumSize(170, 0);
    coordEdit_->setText(tr(coord.toStdString().c_str()));
    auto* okPb = new QPushButton(tr("&OK"));
    okPb->setIcon(QApplication::style()->standardIcon(QStyle::SP_DialogOkButton));
    auto* cancelPb = new QPushButton(tr("&Cancel"));
    cancelPb->setIcon(QApplication::style()->standardIcon(QStyle::SP_DialogCancelButton));
    hlay->addWidget(coordLabel);
    hlay->addWidget(coordEdit_);
    hlay->addStretch(1);
    hlay->addWidget(okPb);
    hlay->addWidget(cancelPb);

    //Setup the actions
    setupZoomActions();
    setupViewActions();
    setupInputSelectionActions();

    //Setup menus and toolbars
    setupMenus(menuItems_, MvQMainWindow::ToolBarOnlyOption);

    isFirstMap_ = true;

    // Signal/Slot definitions
    connect(okPb, SIGNAL(clicked()), this, SLOT(slotOk()));
    connect(cancelPb, SIGNAL(clicked()), this, SLOT(close()));
    connect(coordEdit_, SIGNAL(returnPressed()), this, SLOT(slotCoordChanged()));

    connect(this, SIGNAL(plotWindowUpdated()),
            this, SLOT(slotPlotWindowUpdated()));

    connect(this, SIGNAL(areaChanged(double, double, double, double)),
            plotView_, SLOT(slotChangeArea(double, double, double, double)));

    connect(this, SIGNAL(lineChanged(double, double, double, double)),
            plotView_, SLOT(slotChangeLine(double, double, double, double)));

    connect(this, SIGNAL(pointChanged(double, double)),
            plotView_, SLOT(slotChangePoint(double, double)));

    //Read qt geometry settings
    readSettings();

    //Enable antialias
    slotEnableAntialias(true);

    //Hide view toolbar
    QToolBar* tb = findToolBar(MvQMainWindow::ViewMenu);
    if (tb)
        tb->hide();

    //Size is set to Fit to window
    int sizeIndex = predefSizeValues_.indexOf(uPlotBase::FitToWindow);
    if (sizeIndex != -1)
        sizeCombo_->setCurrentIndex(sizeIndex);
    else
        sizeCombo_->setCurrentIndex(0);
}

GeoTool::~GeoTool()
{
    writeSettings();
}

void GeoTool::setupInputSelectionActions()
{
    //Selection action
    auto* actionSelection = new QAction(this);
    actionSelection->setObjectName(QString::fromUtf8("actionSelection"));
    actionSelection->setCheckable(true);

    QIcon icon;
    if (inputType_ == "AREA") {
        icon.addPixmap(QPixmap(QString::fromUtf8(":/geoSelect/select_rect.svg")), QIcon::Normal, QIcon::Off);
    }
    else if (inputType_ == "LINE") {
        icon.addPixmap(QPixmap(QString::fromUtf8(":/geoSelect/select_line.svg")), QIcon::Normal, QIcon::Off);
    }
    else if (inputType_ == "POINT") {
        icon.addPixmap(QPixmap(QString::fromUtf8(":/geoSelect/select_point.svg")), QIcon::Normal, QIcon::Off);
    }
    actionSelection->setIcon(icon);

    QString selectionName;
    if (inputType_ == "AREA") {
        selectionName = tr("&Area selection");
    }
    else if (inputType_ == "LINE") {
        selectionName = tr("&Line selection");
    }
    else if (inputType_ == "POINT") {
        selectionName = tr("&Point selection");
    }
    actionSelection->setText(selectionName);

    //Clear selection action
    QAction *actionClear, *actionAll, *actionChDir;
    if (inputType_ == "AREA") {
        actionClear = new QAction(this);
        actionClear->setObjectName(QString::fromUtf8("actionClear"));
        actionClear->setCheckable(false);
        actionClear->setText(tr("&Clear selection"));
        QIcon icon1;
        icon1.addPixmap(QPixmap(QString::fromUtf8(":/geoSelect/remove.svg")), QIcon::Normal, QIcon::Off);
        actionClear->setIcon(icon1);

        actionAll = new QAction(this);
        actionAll->setObjectName(QString::fromUtf8("actionAll"));
        actionAll->setCheckable(false);
        actionAll->setText(tr("&Select whole area"));
        QIcon icon2;
        icon2.addPixmap(QPixmap(QString::fromUtf8(":/geoSelect/select_all.svg")), QIcon::Normal, QIcon::Off);
        actionAll->setIcon(icon2);
    }
    else if (inputType_ == "LINE") {
        actionClear = new QAction(this);
        actionClear->setObjectName(QString::fromUtf8("actionClear"));
        actionClear->setCheckable(false);
        actionClear->setText(tr("&Clear selection"));
        QIcon icon1;
        icon1.addPixmap(QPixmap(QString::fromUtf8(":/geoSelect/remove.svg")), QIcon::Normal, QIcon::Off);
        actionClear->setIcon(icon1);

        actionChDir = new QAction(this);
        actionChDir->setObjectName(QString::fromUtf8("actionChDir"));
        actionChDir->setCheckable(false);
        actionChDir->setText(tr("&Change line direction"));
        QIcon icon2;
        icon2.addPixmap(QPixmap(QString::fromUtf8(":/geoSelect/swap_direction.svg")), QIcon::Normal, QIcon::Off);
        actionChDir->setIcon(icon2);
    }
    else if (inputType_ == "POINT") {
        actionClear = new QAction(this);
        actionClear->setObjectName(QString::fromUtf8("actionClear"));
        actionClear->setCheckable(false);
        actionClear->setText(tr("&Clear selection"));
        QIcon icon1;
        icon1.addPixmap(QPixmap(QString::fromUtf8(":/geoSelect/remove.svg")), QIcon::Normal, QIcon::Off);
        actionClear->setIcon(icon1);
    }


    // Connections

    if (inputType_ == "AREA") {
        connect(actionSelection, SIGNAL(toggled(bool)),
                plotView_, SLOT(slotSetEnableAreaSelection(bool)));

        connect(actionSelection, SIGNAL(toggled(bool)),
                coordEdit_, SLOT(setEnabled(bool)));

        connect(actionSelection, SIGNAL(toggled(bool)),
                actionClear, SLOT(setEnabled(bool)));

        connect(actionSelection, SIGNAL(toggled(bool)),
                actionAll, SLOT(setEnabled(bool)));

        connect(plotView_, SIGNAL(areaIsDefined(double, double, double, double)),
                this, SLOT(slotAreaSelection(double, double, double, double)));

        connect(plotView_, SIGNAL(areaIsUndefined()),
                this, SLOT(slotAreaIsUndefined()));

        connect(plotView_, SIGNAL(inputSIsEnabledProgramatically(bool)),
                actionSelection, SLOT(setChecked(bool)));

        connect(actionClear, SIGNAL(triggered()),
                plotView_, SLOT(slotClearArea()));

        connect(actionAll, SIGNAL(triggered()),
                plotView_, SLOT(slotSelectAllArea()));
    }
    else if (inputType_ == "LINE") {
        connect(actionSelection, SIGNAL(toggled(bool)),
                plotView_, SLOT(slotSetEnableLineSelection(bool)));

        connect(actionSelection, SIGNAL(toggled(bool)),
                coordEdit_, SLOT(setEnabled(bool)));

        connect(actionSelection, SIGNAL(toggled(bool)),
                actionClear, SLOT(setEnabled(bool)));

        connect(plotView_, SIGNAL(lineIsDefined(double, double, double, double)),
                this, SLOT(slotLineSelection(double, double, double, double)));

        connect(plotView_, SIGNAL(lineIsUndefined()),
                this, SLOT(slotLineIsUndefined()));

        connect(plotView_, SIGNAL(inputSIsEnabledProgramatically(bool)),
                actionSelection, SLOT(setChecked(bool)));

        connect(actionClear, SIGNAL(triggered()),
                plotView_, SLOT(slotClearLine()));

        connect(actionChDir, SIGNAL(triggered()),
                plotView_, SLOT(slotChangeLineDirection()));
    }
    else if (inputType_ == "POINT") {
        connect(actionSelection, SIGNAL(toggled(bool)),
                plotView_, SLOT(slotSetEnablePointSelection(bool)));

        connect(actionSelection, SIGNAL(toggled(bool)),
                coordEdit_, SLOT(setEnabled(bool)));

        connect(actionSelection, SIGNAL(toggled(bool)),
                actionClear, SLOT(setEnabled(bool)));

        connect(plotView_, SIGNAL(pointIsDefined(double, double)),
                this, SLOT(slotPointSelection(double, double)));

        connect(plotView_, SIGNAL(pointIsUndefined()),
                this, SLOT(slotPointIsUndefined()));

        connect(plotView_, SIGNAL(inputSIsEnabledProgramatically(bool)),
                actionSelection, SLOT(setChecked(bool)));

        connect(actionClear, SIGNAL(triggered()),
                plotView_, SLOT(slotClearPoint()));
    }

    MvQMainWindow::MenuType menuType = MvQMainWindow::SelectionMenu;

    menuItems_[menuType].push_back(new MvQMenuItem(actionSelection));
    if (inputType_ == "AREA") {
        menuItems_[menuType].push_back(new MvQMenuItem(actionAll));
        menuItems_[menuType].push_back(new MvQMenuItem(actionClear));
    }
    else if (inputType_ == "LINE") {
        menuItems_[menuType].push_back(new MvQMenuItem(actionChDir));
        menuItems_[menuType].push_back(new MvQMenuItem(actionClear));
    }
    else if (inputType_ == "POINT") {
        menuItems_[menuType].push_back(new MvQMenuItem(actionClear));
    }


    // Enable icon and call callback function to draw the initial user selection
    actionSelection->setChecked(true);
}

QString GeoTool::InitializeParams(MvRequest& req)
{
    // Create a default superpage request
    spRequest_          = ObjectList::CreateDefaultRequest("PLOT_SUPERPAGE");
    spRequest_("_NAME") = "Geographical Tool Window";

    // Get input type
    // Problem: request MapView comes with MAP and Average with AREA
    // Use input type tag AREA always
    if (const char* cv = req("INPUT_TYPE"))
        inputType_ = std::string(cv);
    else
        return QString("ERROR");

    if (inputType_ == "MAP")
        inputType_ = "AREA";

    //Get the paramater name
    if (const char* cv = req("INPUT_PARAM"))
        inputPar_ = std::string(cv);

    // Update size
    spRequest_("CUSTOM_WIDTH")  = req("CUSTOM_WIDTH");
    spRequest_("CUSTOM_HEIGHT") = req("CUSTOM_HEIGHT");
    spRequest_("LAYOUT_SIZE")   = "CUSTOM";
    req.advance();  // skip EDIT_MAP request

    // Create a coastline request from user's preferences
    MvRequest coastRequest = Preferences::CoastRequest();

    // Create a default mapview request
    // Customize dimensions and add coastlines
    MvRequest viewRequest             = ObjectList::CreateDefaultRequest(DEFAULTVIEW.c_str());
    viewRequest("SUBPAGE_X_POSITION") = 7;
    viewRequest("SUBPAGE_Y_POSITION") = 7;
    viewRequest("SUBPAGE_X_LENGTH")   = 86;
    viewRequest("SUBPAGE_Y_LENGTH")   = 86,
    viewRequest("COASTLINES")         = coastRequest;

    // Initialize parameters
    QString coord;
    geoRequest_.setVerb("INPUT");
    if (inputType_ == "POINT") {
        //If there is no par specified we need to guess it
        if (inputPar_.empty()) {
            if (static_cast<const char*>(req("POINT")))
                inputPar_ = "POINT";
            else if (static_cast<const char*>(req("POSITION")))
                inputPar_ = "POSITION";
            else {
                MvLog().popup().err() << "GeoTool-> Invalid parameter value. Valid values: POINT/POSITION";
                return QString("ERROR");
            }
        }

        geoRequest_(inputPar_.c_str()) = req(inputPar_.c_str(), 0);
        geoRequest_(inputPar_.c_str()) += req(inputPar_.c_str(), 1);
        coord = (const char*)req(inputPar_.c_str(), 0) % QChar('/') % (const char*)req(inputPar_.c_str(), 1);
    }
    else if (inputType_ == "LINE") {
        //If there is no par specified we need to guess it
        if (inputPar_.empty()) {
            if (static_cast<const char*>(req("LINE")))
                inputPar_ = "LINE";
            else {
                MvLog().popup().err() << "GeoTool-> No parameter is specified for line helper";
                return QString("ERROR");
            }
        }

        geoRequest_(inputPar_.c_str()) = req(inputPar_.c_str(), 0);
        geoRequest_(inputPar_.c_str()) += req(inputPar_.c_str(), 1);
        geoRequest_(inputPar_.c_str()) += req(inputPar_.c_str(), 2);
        geoRequest_(inputPar_.c_str()) += req(inputPar_.c_str(), 3);
        coord = requestToCoord(req, inputPar_.c_str());
    }
    else if (inputType_ == "AREA") {
        //If there is no par specified we need to guess it
        if (inputPar_.empty()) {
            if (static_cast<const char*>(req("AREA")))
                inputPar_ = "AREA";
            else if (static_cast<const char*>(req("FLEXTRA_AREA")))
                inputPar_ = "FLEXTRA_AREA";
            else if (static_cast<const char*>(req("area")))
                inputPar_ = "area";
            else {
                MvLog().popup().err() << "GeoTool-> No parameter is specified for area helper";
                return QString("ERROR");
            }
        }

        /*if(static_cast<const char*>(req("AREA")))
	  		areaParam_="AREA";
		else if(static_cast<const char*>(req("FLEXTRA_AREA")))
		  	areaParam_="FLEXTRA_AREA";
		else if(static_cast<const char*>(req("area")))
		  	areaParam_="area";*/

        geoRequest_(inputPar_.c_str()) = req(inputPar_.c_str(), 0);
        geoRequest_(inputPar_.c_str()) += req(inputPar_.c_str(), 1);
        geoRequest_(inputPar_.c_str()) += req(inputPar_.c_str(), 2);
        geoRequest_(inputPar_.c_str()) += req(inputPar_.c_str(), 3);
        coord = requestToCoord(req, inputPar_.c_str());

        if (static_cast<const char*>(req("MAP_PROJECTION"))) {
            geoRequest_("MAP_PROJECTION") = req("MAP_PROJECTION");
            viewRequest("MAP_PROJECTION") = req("MAP_PROJECTION");
        }
        if (static_cast<const char*>(req("MAP_VERTICAL_LONGITUDE"))) {
            geoRequest_("MAP_VERTICAL_LONGITUDE") = req("MAP_VERTICAL_LONGITUDE");
            viewRequest("MAP_VERTICAL_LONGITUDE") = req("MAP_VERTICAL_LONGITUDE");
        }
        if (static_cast<const char*>(req("MAP_HEMISPHERE"))) {
            geoRequest_("MAP_HEMISPHERE") = static_cast<const char*>(req("MAP_HEMISPHERE"));
            viewRequest("MAP_HEMISPHERE") = static_cast<const char*>(req("MAP_HEMISPHERE"));
        }
    }

    // Finalize superpage request
    // Create default page and add view to this request
    MvRequest pageRequest = ObjectList::CreateDefaultRequest("PLOT_PAGE");
    pageRequest("VIEW")   = viewRequest;
    spRequest_("PAGES")   = pageRequest;

    return coord;
}

void GeoTool::UpdateCoordinates(QString& coord)
{
    QStringList clist = coord.split("/");
    if (inputType_ == "POINT") {
        if (clist.size() != 2) {
            MvLog().popup().err() << "GeoTool-> POINT coordinates must have two values";
            return;
        }
        geoRequest_(inputPar_.c_str()) = clist.at(0).toDouble();
        geoRequest_(inputPar_.c_str()) += clist.at(1).toDouble();
    }
    else if (inputType_ == "LINE") {
        if (clist.size() != 4) {
            MvLog().popup().err() << "GeoTool-> LINE coordinates must have 4 values";
            return;
        }
        coordToRequest(coord, geoRequest_, inputPar_.c_str());
    }
    else {
        if (clist.size() != 4) {
            MvLog().popup().err() << "GeoTool UpdateCoordinates-> Expected 4 values for list of coordinates";
            return;
        }
        coordToRequest(coord, geoRequest_, inputPar_.c_str());
    }
    return;
}


void GeoTool::newRequestForDriversBegin()
{
    plotScene_->saveStateBeforeNewRequest();

    if (activeScene_) {
        prevActiveSceneId_ = activeScene_->layout().id();
        if (prevActiveSceneId_.empty()) {
            MgQLayoutItem* projItem = activeScene_->firstProjectorItem();
            prevActiveSceneId_      = projItem->layout().id();
        }
    }
    else {
        prevActiveSceneId_.clear();
    }

    activeScene_ = 0;
}


void GeoTool::newRequestForDriversEnd()
{
    //Select the active scene
    if (!activeScene_) {
        if (!prevActiveSceneId_.empty()) {
            foreach (MgQSceneItem* item, plotScene_->sceneItems()) {
                MgQLayoutItem* projItem = item->firstProjectorItem();
                if (item->layout().id() == prevActiveSceneId_) {
                    activeScene_ = item;
                    break;
                }
                else if (item->layout().id().empty() && projItem &&
                         prevActiveSceneId_ == projItem->layout().id()) {
                    activeScene_ = item;
                    break;
                }
            }
        }


        if (!activeScene_ && plotScene_->sceneItems().count() > 0) {
            activeScene_ = plotScene_->sceneItems().back();
        }
    }

    //Resize without rendering!!
    changeSize(sizeCombo_->itemData(sizeCombo_->currentIndex(), Qt::UserRole).toInt(), false);

    //Load steps/layers and generate layer thumbnails - No rendering at this point!
    //It tries to set the current step for all the scenes!
    //The current step should be correctly set at least for the active scene.
    plotScene_->updateAfterNewRequest();

    //Zoom stack
    zoomStackWidget_->reset(activeScene_, false);
    updateZoomActionState();

    //Magnifier, cursordata etc
    plotView_->resetEnd();

    //NOW RENDER IT! We render the whole scene into the pixmap cache at this point!
    plotScene_->sceneItemChanged();

    //Emit a signal that the plot windows has been updated
    emit plotWindowUpdated();
}


void GeoTool::slotOk()
{
    // Update coordinates
    QString coord = coordEdit_->text();

    if (coord != tr("Undefined")) {
        UpdateCoordinates(coord);
        // Send request back to the caller
        MvApplication::sendMessage(geoRequest_);
    }
    // Close interface
    close();
}

void GeoTool::slotCoordChanged()
{
    // Geographical coordinates changed manually.
    // Update graphical area.
    coord_ = coordEdit_->text();

    QStringList clist = coord_.split("/");
    if (inputType_ == "AREA") {
        double blLat = clist.at(0).toDouble();
        double blLon = clist.at(1).toDouble();
        double trLat = clist.at(2).toDouble();
        double trLon = clist.at(3).toDouble();
        //plotView_->DrawRectangle(north,west,south,east);

        emit areaChanged(blLat, blLon, trLat, trLon);
    }
    else if (inputType_ == "LINE") {
        double lat1 = clist.at(0).toDouble();
        double lon1 = clist.at(1).toDouble();
        double lat2 = clist.at(2).toDouble();
        double lon2 = clist.at(3).toDouble();
        //plotView_->DrawRectangle(north,west,south,east);

        emit lineChanged(lat1, lon1, lat2, lon2);
    }
    else if (inputType_ == "POINT") {
        double lat = clist.at(0).toDouble();
        double lon = clist.at(1).toDouble();

        //plotView_->DrawRectangle(north,west,south,east);

        emit pointChanged(lat, lon);
    }
}

void GeoTool::slotAreaSelection(double blLat, double blLon, double trLat, double trLon)
{
    // A new area was selected graphically. Update text coordinates.
    char buf[48];
    sprintf(buf, "%.2f/%.2f/%.2f/%.2f", blLat, blLon, trLat, trLon);
    coordEdit_->setText(tr(buf));
    coord_ = buf;
}

void GeoTool::slotAreaIsUndefined()
{
    bool editStatus = coordEdit_->isEnabled();
    if (editStatus == false) {
        coordEdit_->setEnabled(true);
    }
    coordEdit_->setText(tr("Undefined"));
    if (editStatus == false) {
        coordEdit_->setEnabled(false);
    }

    coord_.clear();
}

void GeoTool::slotLineSelection(double lat1, double lon1, double lat2, double lon2)
{
    // A new area was selected graphically. Update text coordinates.
    char buf[48];
    sprintf(buf, "%.2f/%.2f/%.2f/%.2f", lat1, lon1, lat2, lon2);
    coordEdit_->setText(tr(buf));
    coord_ = buf;
}

void GeoTool::slotLineIsUndefined()
{
    bool editStatus = coordEdit_->isEnabled();
    if (editStatus == false) {
        coordEdit_->setEnabled(true);
    }
    coordEdit_->setText(tr("Undefined"));
    if (editStatus == false) {
        coordEdit_->setEnabled(false);
    }

    coord_.clear();
}

void GeoTool::slotPointSelection(double lat, double lon)
{
    // A new area was selected graphically. Update text coordinates.
    char buf[48];
    sprintf(buf, "%.2f/%.2f", lat, lon);
    coordEdit_->setText(tr(buf));
    coord_ = buf;
}

void GeoTool::slotPointIsUndefined()
{
    bool editStatus = coordEdit_->isEnabled();
    if (editStatus == false) {
        coordEdit_->setEnabled(true);
    }
    coordEdit_->setText(tr("Undefined"));
    if (editStatus == false) {
        coordEdit_->setEnabled(false);
    }

    coord_.clear();
}


void GeoTool::slotPlotWindowUpdated()
{
    if (inputType_ == "AREA") {
        if (isFirstMap_ == true) {
            //plotView_->slotSelectAllArea();
            slotCoordChanged();
            isFirstMap_ = false;
        }
        //slotCoordChanged();
    }
    else if (inputType_ == "LINE") {
        if (isFirstMap_ == true) {
            slotCoordChanged();
            isFirstMap_ = false;
        }
        //slotCoordChanged();
    }
    else if (inputType_ == "POINT") {
        if (isFirstMap_ == true) {
            slotCoordChanged();
            isFirstMap_ = false;
        }
        //slotCoordChanged();
    }
}

//void GeoTool::slotClearSelection()
//{
//	slotAreaIsUndefined();
//	plotView_->slotClearArea();
//}

QString GeoTool::requestToCoord(MvRequest& req, const char* param)
{
    if (!param)
        return QString();

    QString coord = (const char*)req(param, 0) % QChar('/') %
                    (const char*)req(param, 1) % QChar('/') %
                    (const char*)req(param, 2) % QChar('/') %
                    (const char*)req(param, 3);

    return coord;
}

void GeoTool::coordToRequest(QString& coord, MvRequest& req, const char* param)
{
    QStringList clist = coord.split("/");

    req(param) = clist.at(0).toDouble();
    req(param) += clist.at(1).toDouble();
    req(param) += clist.at(2).toDouble();
    req(param) += clist.at(3).toDouble();

    return;
}

bool GeoTool::setDropTarget(QPoint globalPos)
{
    QPointF scenePos = plotView_->mapToScene(plotView_->mapFromGlobal(globalPos));

    if (activeScene_ && activeScene_->sceneBoundingRect().contains(scenePos)) {
        return true;
    }

    return false;
}

bool GeoTool::setDropTargetInView(QPoint pos)
{
    QPointF scenePos = plotView_->mapToScene(pos);

    if (activeScene_ && activeScene_->sceneBoundingRect().contains(scenePos)) {
        return true;
    }

    return false;
}

void GeoTool::writeSettings()
{
    QSettings settings(MVQ_QSETTINGS_DEFAULT_ARGS, "MV4-GeoTool");
    settings.beginGroup("main");
    settings.setValue("geometry", saveGeometry());
    settings.setValue("state", saveState());
    settings.endGroup();
}

void GeoTool::readSettings()
{
    QSettings settings(MVQ_QSETTINGS_DEFAULT_ARGS, "MV4-GeoTool");
    settings.beginGroup("main");
    restoreGeometry(settings.value("geometry").toByteArray());
    restoreState(settings.value("state").toByteArray());
    settings.endGroup();
}
