#include "alarmdialog.h"
#include "ui_alarmdialog.h"
#include "qcustomplot.h"

#include <QGeoCoordinate>
#include <QQmlContext>
#include <QColor>

alarmdialog::alarmdialog(QDialog *parent,
                         const QString &sensorId,
                         const QString &sensorName,
                         const QString &group,
                         const QString &dateStart,
                         const QString &dateEnd,
                         SensorService *sensorService)
    : QDialog(parent)
    , ui(new Ui::alarmdialog)
    , _sensorService(sensorService)
{
    ui->setupUi(this);

    ui->nameHead->setText(sensorId);
    ui->name->setText("Датчик - " + sensorName);
    ui->dateStart->setText("Дата начала - " + dateStart);
    if(dateEnd.isEmpty()) {
        ui->dateEnd->setText("Дата конца - Инцидент еще не закончился");
    } else {
        ui->dateEnd->setText("Дата конца - " + dateEnd);
    }

    QCustomPlot *customPlot = new QCustomPlot(this);

    customPlot->setFixedSize(710, 250);

    ui->chartLayout->addWidget(customPlot);

    qint64 start = QDateTime::fromString(dateStart, "dd.MM.yyyy HH:mm").toSecsSinceEpoch();
    qint64 end = QDateTime::fromString(dateEnd, "dd.MM.yyyy HH:mm").toSecsSinceEpoch();
    if(end == 0) {
        end = QDateTime::currentMSecsSinceEpoch();
    }
    PlotData data = sensorService->getDeviceSensorData(group, sensorId, start, end);

    customPlot->addGraph();
    QPen pen;
    pen.setColor(QColor(19, 58, 97));
    pen.setWidth(2);
    customPlot->graph(0)->setPen(pen);
    customPlot->graph(0)->setData(data.X, data.Y);

    QSharedPointer<QCPAxisTickerDateTime> dateTimeTicker(new QCPAxisTickerDateTime);
    dateTimeTicker->setDateTimeFormat("HH:mm:ss dd.MM.yyyy");
    customPlot->xAxis->setTicker(dateTimeTicker);

    customPlot->yAxis->setRange(*std::min_element(data.Y.begin(), data.Y.end()) - 10,
                                *std::max_element(data.Y.begin(), data.Y.end()) + 10);

    customPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom);

    customPlot->graph(0)->rescaleAxes();
    customPlot->replot();


    QVariantList points = sensorService->getPoints(start, end);

    if(!points.empty()) {
        ui->map->rootContext()->setContextProperty("mapCenter", points[0]);
        ui->map->rootContext()->setContextProperty("pointsList", points);
    }

    ui->map->setSource(QUrl(QStringLiteral("qrc:/qml/map.qml")));

    connect(ui->cancelButton, &QPushButton::clicked, this, &alarmdialog::onCancelButtonClicked);
    connect(ui->statisticButton, &QPushButton::clicked, this, &alarmdialog::onStatisticButtonClicked);
}

void alarmdialog::onCancelButtonClicked()
{
    this->close();
}

void alarmdialog::onStatisticButtonClicked()
{
    emit dialogClosed();
    this->close();
}

alarmdialog::~alarmdialog()
{
    delete ui;
}
