#include <QDebug>
#include <QDoubleValidator>
#include <QEventLoop>
#include <QGridLayout>
#include <QJsonDocument>
#include <QJsonObject>
#include <QMessageBox>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QTimer>

#include "CalibrationEditDialog_DXC220.h"
#include "Config.h"
#include "TUSBProvider.h"

#define CONCENTRATION_MIN 0
#define CONCENTRATION_MAX 220000

CalibrationEditDialog_DXC220::CalibrationEditDialog_DXC220(QWidget *parent, const QString &serialNumber,
                                                           const bool localTenkinet)
    : QDialog(parent), serialNumber(serialNumber), localTenkinet(localTenkinet) {
    QDoubleValidator *valueValidator;
    int pref_unit;

    btn_ok = new QPushButton(tr("OK"));
    btn_ok->setDefault(true);
    btn_cancel = new QPushButton(tr("Cancel"));

    connect(btn_ok, SIGNAL(clicked()), this, SLOT(applyClose()));
    connect(btn_cancel, SIGNAL(clicked()), this, SLOT(close()));
    setWindowTitle(tr("Calibrate channel"));

    QGridLayout *gridLayout = new QGridLayout();

    QLabel *label = new QLabel("Concentration (ppm)");
    concentrationEdit = new QLineEdit();
    valueValidator = new QDoubleValidator(this);
    valueValidator->setRange(CONCENTRATION_MIN, CONCENTRATION_MAX, 0);
    concentrationEdit->setValidator(valueValidator);
    gridLayout->addWidget(label, 0, 0);
    gridLayout->addWidget(concentrationEdit, 0, 1);

    QHBoxLayout *lay_btns = new QHBoxLayout();
    lay_btns->addStretch();
    lay_btns->addWidget(btn_cancel);
    lay_btns->addWidget(btn_ok);

    QVBoxLayout *lay_vert = new QVBoxLayout();

    lay_vert->addSpacing(10);
    lay_vert->addSpacing(10);
    lay_vert->addStretch();
    lay_vert->addLayout(gridLayout);
    lay_vert->addLayout(lay_btns);

    setLayout(lay_vert);
    setModal(true);
}

CalibrationEditDialog_DXC220::~CalibrationEditDialog_DXC220() {}

void CalibrationEditDialog_DXC220::applyClose() {
    if (concentrationEdit->hasAcceptableInput()) {
        QString value = concentrationEdit->text();

        TUSBProvider::instance().set_DXC220_KZ(serialNumber, value.toInt());
        close();
    } else {
        QMessageBox msgBox;
        QString message;
        message.sprintf("Value must be between %d and %d ppm", CONCENTRATION_MIN, CONCENTRATION_MAX);
        msgBox.setIcon(QMessageBox::Information);
        msgBox.setText(message);
        msgBox.exec();
    }
}
