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

 Copyright 2023 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 <QtGlobal>
#include <QAction>
#include <QString>

#include "LocationLabelWidget.h"
#include "CursorCoordinate.h"
#include "MvQMethods.h"


namespace metview {
namespace uplot {

LocationLabelWidget::LocationLabelWidget(QWidget* parent) : QLabel(parent)
{
    setProperty("type", "location");
    setText("Location");
    setFont(MvQ::findMonospaceFont(true));

    viewAction_ = new QAction(this);
    viewAction_->setText(tr("Show location label"));
    viewAction_->setCheckable(true);
    viewAction_->setChecked(true);

    connect(viewAction_, SIGNAL(toggled(bool)),
            this, SLOT(setVisible(bool)));
}

void LocationLabelWidget::setLocation(const CursorCoordinate& coord) {

    QString t;
    static QString invalidText("Cursor outside plot area");
    if (coord.isValid()) {
        if (coord.type() ==  CursorCoordinate::LonLatType) {
            QString x, y;
#if QT_VERSION >= QT_VERSION_CHECK(5, 5, 0)
            x = QString::asprintf("%7.3f", coord.y());
            y = QString::asprintf("%8.3f", coord.x());
#else
            QString dummyStr;
            x = dummyStr.sprintf("%7.3f", coord.y());
            y = dummyStr.sprintf("%8.3f", coord.x());
#endif
            t = "<b>Lat:</b> " + x + " <b>Lon:</b> " + y  ;

        } else {
            t = QString("<b>X:</b> %1 <b>Y:</b> %2").arg(coord.y(), 0, 'f', 3).arg(coord.x(), 0, 'f',3);
        }
    } else {
        t = invalidText;
    }

    if (t != text()) {
        setText(t);
    }
}

void LocationLabelWidget::writeSettings(QSettings& settings)
{
    settings.setValue("locationLabel", viewAction_->isChecked());
}

void LocationLabelWidget::readSettings(QSettings& settings)
{
    if (settings.value("locationLabel").isNull()) {
        viewAction_->setChecked(true);
    }
    else {
        viewAction_->setChecked(settings.value("locationLabel").toBool());
    }
}

} // uplot
} // metview
