#include "bmssettings.h"
#include "ui_bmssettings.h"

#include "widgets/paramtable.h"
#include "widgets/parameditdouble.h"
#include "configparamsgetter.h"

#include <QIntValidator>
#include <QDoubleValidator>
#include <QMessageBox>
#include <QFileDialog>

BmsSettings::BmsSettings(QWidget *parent) :
    QFrame(parent),
    ui(new Ui::BmsSettings)
{
    ui->setupUi(this);

    ui->pbWriteToNonVolatileBmsMemory->hide();
    ui->pbWriteCurrentValuesToBms->hide();

    // https://localcoder.org/set-qlineedit-to-accept-only-numbers
    ui->editSerialNumber->setValidator(new QRegExpValidator(QRegExp("[1-9][0-9]*"), this)); // only numbers //  leading digit must be 1 to 9 (prevents leading zeroes).

    ui->editGroupsNumber->setValidator( new QIntValidator(-1000, 1000, this) );
    ui->editCellsNumber->setValidator( new QIntValidator(-1000, 1000, this) );

    ui->editCellsInParallelGroup->setValidator( new QIntValidator(1, 1000, this) );
    ui->editBatteryCapacity->setValidator( new QIntValidator(0, 10000, this) );

    ui->editMaxVoltageCharge->setValidator( new QIntValidator(-1000, 1000, this) );
    ui->editMaxCircuitLoad->setValidator( new QIntValidator(-1000, 10000, this) );
    ui->editMaxTemperature->setValidator( new QIntValidator(-1000, 1000, this) );

    ui->editMinVoltageWhenWeTurnLoadOff->setValidator( new QDoubleValidator(-100, 100, 2, this) );
    ui->editSuchVoltageWhenWeTurnLoadOn->setValidator( new QDoubleValidator(-100, 100, 2, this) );
    ui->editSuchVoltageWhenWeTurnChargeOn->setValidator( new QDoubleValidator(-100, 100, 2, this) );
    ui->editMaxVoltageWhenWeTurnChargeOff->setValidator( new QDoubleValidator(-100, 100, 2, this) );

    ui->editVoltageBalancingStart->setValidator( new QDoubleValidator(-100, 100, 2, this) );
    ui->editVoltageDifferenceThreshold->setValidator( new QDoubleValidator(-100, 100, 2, this) );
    ui->editCellBalancingInterval->setValidator( new QIntValidator(-1000, 100000, this) );

    //V
    //ui->cboxUseToManageStorageDevice
    //ui->cboxNormallyClosed
    ui->editSocValueEdit->setValidator( new QDoubleValidator(-100, 100, 2, this) );

    //ui->cboxTemperatureSettingsOver
    ui->editTemperatureIfLessThenCloseOver->setValidator( new QIntValidator(-1000, 1000, this) );
    ui->editTemperatureIfMoeeThenOpenOver->setValidator( new QIntValidator(-1000, 1000, this) );

    //ui->cboxTemperatureSettingsUnder
    ui->editTemperatureIfLessThenCloseUnder->setValidator( new QIntValidator(-1000, 1000, this) );
    ui->editTemperatureIfMoeeThenOpenUnder->setValidator( new QIntValidator(-1000, 1000, this) );

    ui->editPointZeroDetectorValue->setValidator( new QDoubleValidator(-1000, 1000, 2, this) );

    // BTNS
    //ui->pbCalibrateZeroPoint
    //ui->pbWriteIntoNonVolatileMemoryOfBsm
    //ui->pbWriteCurrentValuesIntoBsm

    connect(ui->pbSaveBMSConfToXmlFile, &QPushButton::clicked, this, &BmsSettings::onSaveBMSConfToXmlFileClicked);
    connect(ui->pbLoadBMSConfFromXmlFile, &QPushButton::clicked, this, &BmsSettings::onLoadBMSConfFromXmlFileClicked);


    clearControlls();
}

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

//

void BmsSettings::onBmsconfUpdateRequested()
{
    int a = 1;
}

void BmsSettings::onBmsconfUpdateRequestDefault()
{
    int a = 1;
}

void BmsSettings::onBmsconfUpdated()
{
    // ^  -   8     7 |   8    8 read bms conf
    // After we hav red real BMS Config params from BMS we put all of them into the GUI elements

    // Load default params from Bms to GUI Elements
    //-> -   7     7 |   7    8 read default 8 is defaul - that was on the start
    // Загрузить настройки\nпо умолчанию
    //mDieBieMS->commands()->getBMSconfDefault();

    onLoadParams();
}

void BmsSettings::onBmsconfStored()
{
    int a = 1;
}


void BmsSettings::clearControlls()
{
    ui->editSerialNumber ->clear();

    ui->editGroupsNumber                    ->clear();
    ui->editCellsNumber                     ->clear();

    ui->editCellsInParallelGroup            ->clear();
    ui->editBatteryCapacity                 ->clear();

    ui->editMaxVoltageCharge                ->clear();
    ui->editMaxCircuitLoad                  ->clear();
    ui->editMaxTemperature                  ->clear();

    ui->editMinVoltageWhenWeTurnLoadOff     ->clear();
    ui->editSuchVoltageWhenWeTurnLoadOn     ->clear();
    ui->editSuchVoltageWhenWeTurnChargeOn   ->clear();
    ui->editMaxVoltageWhenWeTurnChargeOff   ->clear();


    ui->editVoltageBalancingStart           ->clear();
    ui->editVoltageDifferenceThreshold      ->clear();
    ui->editCellBalancingInterval           ->clear();

    //1
    ui->cboxUseToManageStorageDevice        ->setChecked(false);
    //2
    ui->cboxNormallyClosed                  ->setChecked(false);
    ui->editSocValueEdit                    ->clear();
    //3
    ui->cboxTemperatureSettingsOver         ->setChecked(false);
    ui->editTemperatureIfLessThenCloseOver  ->clear();
    ui->editTemperatureIfMoeeThenOpenOver   ->clear();
    //4
    ui->cboxTemperatureSettingsUnder        ->setChecked(false);
    ui->editTemperatureIfLessThenCloseUnder ->clear();
    ui->editTemperatureIfMoeeThenOpenUnder  ->clear();
    // 0
    ui->editPointZeroDetectorValue        ->clear();
}

void BmsSettings::prepareSettersFromGuiControlsToSettingsFile()
{
    /// Setters
    #define QS QString

    auto cfg = mDieBieMS->bmsConfig();

    /// Серийный номер * //ui->editSerialNumber
    connect(ui->editSerialNumber, &QLineEdit::textChanged, this, [this, cfg]()
    {
        QS s =ui->editSerialNumber->text();
        QVariant val((s.isEmpty() || s=="-") ? 0 : s.toInt());
        cfg->setParamValue("notUsedCurrentThreshold", val);
    });

    /// Конфигурация *
    connect(ui->editGroupsNumber, &QLineEdit::textChanged, this, [this, cfg]()
    { QS s =ui->editGroupsNumber->text(); QVariant val((s.isEmpty() || s=="-") ? 0 : s.toInt()); cfg->setParamValue("cellMonitorICCount", val); });
    connect(ui->editCellsNumber, &QLineEdit::textChanged, this, [this, cfg]()
    {
        QS s =ui->editCellsNumber->text();
        QVariant val((s.isEmpty() || s=="-") ? 0 : s.toInt());
        cfg->setParamValue("noOfCellsSeries", val);
    });
    // Конфигурация *
    //addParamRow(ui->editGroupsNumber                  , mDieBieMS->bmsConfig(), "cellMonitorICCount");
    //addParamRow(ui->editCellsNumber                   , mDieBieMS->bmsConfig(), "noOfCellsSeries");

    /// SOC *
    connect(ui->editCellsInParallelGroup, &QLineEdit::textChanged, this, [this, cfg]()
    { QS s =ui->editCellsInParallelGroup->text(); QVariant val((s.isEmpty() || s=="-") ? 0 : s.toInt()); cfg->setParamValue("noOfCellsParallel", val); });
    connect(ui->editBatteryCapacity, &QLineEdit::textChanged, this, [this, cfg]()
    { QS s =ui->editBatteryCapacity->text(); QVariant val((s.isEmpty() || s=="-") ? 0 : s.toInt()); cfg->setParamValue("batteryCapacity", val); });
    // SOC *
    //addParamRow(ui->editCellsInParallelGroup          , mDieBieMS->bmsConfig(), "noOfCellsParallel");
    //addParamRow(ui->editBatteryCapacity               , mDieBieMS->bmsConfig(), "batteryCapacity");

    /// Ограничения *
    connect(ui->editMaxVoltageCharge, &QLineEdit::textChanged, this, [this, cfg]()
    { QS s =ui->editMaxVoltageCharge->text(); QVariant val((s.isEmpty() || s=="-") ? 0 : s.toInt()); cfg->setParamValue("maxAllowedCurrent", val); });
    connect(ui->editMaxCircuitLoad, &QLineEdit::textChanged, this, [this, cfg]()
    { QS s =ui->editMaxCircuitLoad->text(); QVariant val((s.isEmpty() || s=="-") ? 0 : s.toInt()); cfg->setParamValue("maxMismatchThreshold", val); });
    connect(ui->editMaxTemperature, &QLineEdit::textChanged, this, [this, cfg]()
    { QS s =ui->editMaxTemperature->text(); QVariant val((s.isEmpty() || s=="-") ? 0 : s.toInt()); cfg->setParamValue("allowedTempBattChargingMax", val); });
    // Ограничения *
    //addParamRow(ui->editMaxVoltageCharge              , mDieBieMS->bmsConfig(), "maxAllowedCurrent");
    //addParamRow(ui->editMaxCircuitLoad                , mDieBieMS->bmsConfig(), "maxMismatchThreshold");
    //addParamRow(ui->editMaxTemperature                , mDieBieMS->bmsConfig(), "allowedTempBattChargingMax");

    /// Конфигурация ячеек *
    connect(ui->editMinVoltageWhenWeTurnLoadOff, &QLineEdit::textChanged, this, [this, cfg]()
    { QS s =ui->editMinVoltageWhenWeTurnLoadOff->text(); QVariant val((s.isEmpty() || s=="-") ? 0 : s.toDouble()); cfg->setParamValue("cellHardUnderVoltage", val); });
    connect(ui->editSuchVoltageWhenWeTurnLoadOn, &QLineEdit::textChanged, this, [this, cfg]()
    { QS s =ui->editSuchVoltageWhenWeTurnLoadOn->text(); QVariant val((s.isEmpty() || s=="-") ? 0 : s.toDouble()); cfg->setParamValue("cellHardOverVoltage", val); });
    connect(ui->editSuchVoltageWhenWeTurnChargeOn, &QLineEdit::textChanged, this, [this, cfg]()
    { QS s =ui->editSuchVoltageWhenWeTurnChargeOn->text(); QVariant val((s.isEmpty() || s=="-") ? 0 : s.toDouble()); cfg->setParamValue("cellLCSoftUnderVoltage", val); });
    connect(ui->editMaxVoltageWhenWeTurnChargeOff, &QLineEdit::textChanged, this, [this, cfg]()
    { QS s =ui->editMaxVoltageWhenWeTurnChargeOff->text(); QVariant val((s.isEmpty() || s=="-") ? 0 : s.toDouble()); cfg->setParamValue("cellSoftOverVoltage", val); });
    // Конфигурация ячеек *
    //addParamRow(ui->editMinVoltageWhenWeTurnLoadOff   , mDieBieMS->bmsConfig(), "cellHardUnderVoltage");
    //addParamRow(ui->editSuchVoltageWhenWeTurnLoadOn   , mDieBieMS->bmsConfig(), "cellHardOverVoltage");
    //addParamRow(ui->editSuchVoltageWhenWeTurnChargeOn , mDieBieMS->bmsConfig(), "cellLCSoftUnderVoltage");
    //addParamRow(ui->editMaxVoltageWhenWeTurnChargeOff , mDieBieMS->bmsConfig(), "cellSoftOverVoltage");

    /// Конфигурация балансировки *     // ui->balancingTab
    connect(ui->editVoltageBalancingStart, &QLineEdit::textChanged, this, [this, cfg]()
    { QS s =ui->editVoltageBalancingStart->text(); QVariant val((s.isEmpty() || s=="-") ? 0 : s.toDouble()); cfg->setParamValue("cellBalanceStart", val); });
    connect(ui->editVoltageDifferenceThreshold, &QLineEdit::textChanged, this, [this, cfg]()
    { QS s =ui->editVoltageDifferenceThreshold->text();  QVariant val((s.isEmpty() || s=="-") ? 0 : s.toDouble()); cfg->setParamValue("cellBalanceDifferenceThreshold", val); });
    connect(ui->editCellBalancingInterval, &QLineEdit::textChanged, this, [this, cfg]()
    { QS s =ui->editCellBalancingInterval->text();  QVariant val((s.isEmpty() || s=="-") ? 0 : s.toInt()); cfg->setParamValue("cellBalanceUpdateInterval", val); });
    // Конфигурация балансировки *     // ui->balancingTab
    //addParamRow(ui->editVoltageBalancingStart           , mDieBieMS->bmsConfig(), "cellBalanceStart");
    //addParamRow(ui->editVoltageDifferenceThreshold      , mDieBieMS->bmsConfig(), "cellBalanceDifferenceThreshold");
    //addParamRow(ui->editCellBalancingInterval           , mDieBieMS->bmsConfig(), "cellBalanceUpdateInterval");

    /// Калибровать Нулевую точку *     // ui->signalsTab
    connect(ui->editPointZeroDetectorValue, &QLineEdit::textChanged, this, [this, cfg]()
    {
        QS s =ui->editPointZeroDetectorValue->text();
        QVariant val((s.isEmpty() || s=="-") ? 0 : s.toDouble());
        cfg->setParamValue("shuntLCFactor", val);
    });
    // Нулевая точка *     // ui->signalsTab
    //addParamRow(ui->editPointZeroDetectorValue          , mDieBieMS->bmsConfig(), "shuntLCFactor");
}

void BmsSettings::onLoadParams()
{
    ////

    // Серийный номер * //ui->editSerialNumber
    getSerialNumber(ui->editSerialNumber              , mDieBieMS->bmsConfig(), "notUsedCurrentThreshold");
    // Конфигурация *
    addParamRow(ui->editGroupsNumber                  , mDieBieMS->bmsConfig(), "cellMonitorICCount");
    addParamRow(ui->editCellsNumber                   , mDieBieMS->bmsConfig(), "noOfCellsSeries");
    // SOC *
    addParamRow(ui->editCellsInParallelGroup          , mDieBieMS->bmsConfig(), "noOfCellsParallel");
    addParamRow(ui->editBatteryCapacity               , mDieBieMS->bmsConfig(), "batteryCapacity");
    // Ограничения *
    addParamRow(ui->editMaxVoltageCharge              , mDieBieMS->bmsConfig(), "maxAllowedCurrent");
    addParamRow(ui->editMaxCircuitLoad                , mDieBieMS->bmsConfig(), "maxMismatchThreshold");
    addParamRow(ui->editMaxTemperature                , mDieBieMS->bmsConfig(), "allowedTempBattChargingMax");
    // Конфигурация ячеек *
    addParamRow(ui->editMinVoltageWhenWeTurnLoadOff   , mDieBieMS->bmsConfig(), "cellHardUnderVoltage");
    addParamRow(ui->editSuchVoltageWhenWeTurnLoadOn   , mDieBieMS->bmsConfig(), "cellHardOverVoltage");
    addParamRow(ui->editSuchVoltageWhenWeTurnChargeOn , mDieBieMS->bmsConfig(), "cellLCSoftUnderVoltage");
    addParamRow(ui->editMaxVoltageWhenWeTurnChargeOff , mDieBieMS->bmsConfig(), "cellSoftOverVoltage");
    // Конфигурация балансировки *
    // ui->balancingTab
    addParamRow(ui->editVoltageBalancingStart           , mDieBieMS->bmsConfig(), "cellBalanceStart");
    addParamRow(ui->editVoltageDifferenceThreshold      , mDieBieMS->bmsConfig(), "cellBalanceDifferenceThreshold");
    addParamRow(ui->editCellBalancingInterval           , mDieBieMS->bmsConfig(), "cellBalanceUpdateInterval");
    // Нулевая точка *
    // ui->signalsTab
    addParamRow(ui->editPointZeroDetectorValue          , mDieBieMS->bmsConfig(), "shuntLCFactor");
    ////*/

    // Turn ON Setters only AFTER we load all data from file

    prepareSettersFromGuiControlsToSettingsFile();

    // Turn ON Setters only AFTER we load all data from file


    /*
        <cellBalanceStart>
            <longName>Cell balance start voltage</longName>

        cellMonitorICCount ->
        noOfCellsSeries ->
        --
        noOfCellsParallel ->
        <batteryCapacity>
            <longName>Battery capacity total</longName>
        --
        <maxMismatchThreshold>
            <longName>Mismatch threshold</longName>
        <maxAllowedCurrent>
            <longName>Max allowed current</longName>
        <allowedTempBattChargingMax>
            <longName>Battery temperature charging max</longName>
        --
        <cellHardUnderVoltage>
            <longName>Cell hard undervoltage</longName>
        <cellHardOverVoltage>
            <longName>Cell hard overvoltage</longName>
        <cellLCSoftUnderVoltage>
            <longName>Cell low current soft undervoltage</longName>
        <cellSoftOverVoltage>
            <longName>Cell soft overvoltage</longName>
        --
    */


/*
#if 0
        ConfigParam *p = mDieBieMS->infoConfig()->getParam("master_setting_description");
        if (p != 0) {
            ui->textEdit->setHtml(p->description);
        } else {
            ui->textEdit->setText("Master Setting Description not found.");
        }
#endif
        ConfigParams *const conf = mDieBieMS->bmsConfig();
        ///ParamTable *const pt = new ParamTable(this); //ui->masterStateTab;
        ///pt->addRowSeparator(tr("Current"));
        // Нулевая точка
        addParamRow(ui->editPointZeroDetectorValue          , mDieBieMS->bmsConfig(), "shuntLCFactor");
        //pt->addParamRow(conf, "shuntLCFactor");
        ////pt->addParamRow(conf, "shuntOffset");

        ///pt->addRowSeparator(tr("Pack configuration"));
#if 0   // disable
        pt->addParamRow(conf, "cellMonitorICType");
#endif
        // Конфигурация
        addParamRow(ui->editGroupsNumber                  , mDieBieMS->bmsConfig(), "cellMonitorICCount");
        addParamRow(ui->editCellsNumber                   , mDieBieMS->bmsConfig(), "noOfCellsSeries");
        //pt->addParamRow(conf, "cellMonitorICCount");
        ///pt->addParamRow(conf, "noOfParallelModules");
        //pt->addParamRow(conf, "noOfCellsSeries");

        ///pt->addRowSeparator(tr("SOC - Pack capacity"));
        //pt->addParamRow(conf, "noOfCellsParallel");
        //pt->addParamRow(conf, "batteryCapacity");
        // SOC
        addParamRow(ui->editCellsInParallelGroup          , mDieBieMS->bmsConfig(), "noOfCellsParallel");
        addParamRow(ui->editBatteryCapacity               , mDieBieMS->bmsConfig(), "batteryCapacity");

        ///pt->addRowSeparator(tr("Cell specifications"));
        //pt->addParamRow(conf, "cellHardUnderVoltage");
        //pt->addParamRow(conf, "cellHardOverVoltage");
        //pt->addParamRow(conf, "cellLCSoftUnderVoltage");
        //pt->addParamRow(conf, "cellSoftOverVoltage");
        // Конфигурация ячеек
        addParamRow(ui->editMinVoltageWhenWeTurnLoadOff   , mDieBieMS->bmsConfig(), "cellHardUnderVoltage");
        addParamRow(ui->editSuchVoltageWhenWeTurnLoadOn   , mDieBieMS->bmsConfig(), "cellHardOverVoltage");
        addParamRow(ui->editSuchVoltageWhenWeTurnChargeOn , mDieBieMS->bmsConfig(), "cellLCSoftUnderVoltage");
        addParamRow(ui->editMaxVoltageWhenWeTurnChargeOff , mDieBieMS->bmsConfig(), "cellSoftOverVoltage");

        ///pt->addRowSeparator(tr("Balancing configuration"));
        //pt->addParamRow(conf, "cellBalanceStart");
        //pt->addParamRow(conf, "cellBalanceDifferenceThreshold");
        //pt->addParamRow(conf, "cellBalanceUpdateInterval");
        // Конфигурация балансировки
        // ui->balancingTab
        addParamRow(ui->editVoltageBalancingStart           , mDieBieMS->bmsConfig(), "cellBalanceStart");
        addParamRow(ui->editVoltageDifferenceThreshold      , mDieBieMS->bmsConfig(), "cellBalanceDifferenceThreshold");
        addParamRow(ui->editCellBalancingInterval           , mDieBieMS->bmsConfig(), "cellBalanceUpdateInterval");

        ///pt->addRowSeparator(tr("SoC general"));
#if 0   // disable
        pt->addParamRow(conf, "stateOfChargeStoreInterval");
        pt->addParamRow(conf, "timeoutChargeCompleted");
        pt->addParamRow(conf, "timeoutChargingCompletedMinimalMismatch");
#endif
        ///pt->addParamRow(conf, "minimalPrechargePercentage"); // from pagemastersettings.cpp
        ///pt->addParamRow(conf, "timeoutLCPreCharge"); // from pagemastersettings.cpp

        ///pt->addRowSeparator(tr("Limits"));
        //pt->addParamRow(conf, "maxMismatchThreshold");
        //pt->addParamRow(conf, "maxAllowedCurrent");
        // Ограничения
        addParamRow(ui->editMaxVoltageCharge              , mDieBieMS->bmsConfig(), "maxAllowedCurrent");
        addParamRow(ui->editMaxCircuitLoad                , mDieBieMS->bmsConfig(), "maxMismatchThreshold");
        addParamRow(ui->editMaxTemperature                , mDieBieMS->bmsConfig(), "allowedTempBattChargingMax");

#if 0
        pt->addParamRow(conf, "allowedTempBattDischargingMax");
        pt->addParamRow(conf, "allowedTempBattDischargingMin");
#endif
        //pt->addParamRow(conf, "allowedTempBattChargingMax");
        ///pt->addParamRow(conf, "allowedTempBattChargingMin");
#if 0   // disable
        ///pt->addRowSeparator(tr("NTC specifications battery"));
        pt->addParamRow(mDieBieMS->bmsConfig(), "noOfTempSensorPerModule");
        pt->addParamRow(mDieBieMS->bmsConfig(), "NTCLTC25Deg");
        ///pt->addRowSeparator(tr("NTC specifications expansion Board"));
        pt->addParamRow(mDieBieMS->bmsConfig(), "noOfExpansionBoard");
        pt->addParamRow(mDieBieMS->bmsConfig(), "noOfTempSensorPerExpansionBoard");
#endif
*/

}


BMSInterface *BmsSettings::bms() const
{
    return mDieBieMS;
}

void BmsSettings::setDieBieMS(BMSInterface *dieBieMS)
{ // void PageMasterSettings::setDieBieMS(BMSInterface *dieBieMS)

    mDieBieMS = dieBieMS;

    //pt = new ParamTable(this); //ui->masterStateTab;

    //onLoadParams();

/*
    if (mDieBieMS) {
#if 0
        ConfigParam *p = mDieBieMS->infoConfig()->getParam("master_setting_description");
        if (p != 0) {
            ui->textEdit->setHtml(p->description);
        } else {
            ui->textEdit->setText("Master Setting Description not found.");
        }
#endif
        ConfigParams *const conf = mDieBieMS->bmsConfig();
        ParamTable *const pt = new ParamTable(this); //ui->masterStateTab;
        pt->addRowSeparator(tr("Current"));
        pt->addParamRow(conf, "shuntLCFactor");
        pt->addParamRow(conf, "shuntOffset");

        pt->addRowSeparator(tr("Pack configuration"));
#if 0  // disable
        pt->addParamRow(conf, "cellMonitorICType");
#endif
        pt->addParamRow(conf, "cellMonitorICCount");
        pt->addParamRow(conf, "noOfParallelModules");
        pt->addParamRow(conf, "noOfCellsSeries");

        pt->addRowSeparator(tr("SOC - Pack capacity"));
        pt->addParamRow(conf, "noOfCellsParallel");
        pt->addParamRow(conf, "batteryCapacity");

        pt->addRowSeparator(tr("Cell specifications"));
        pt->addParamRow(conf, "cellHardUnderVoltage");
        pt->addParamRow(conf, "cellHardOverVoltage");
        pt->addParamRow(conf, "cellLCSoftUnderVoltage");
        pt->addParamRow(conf, "cellSoftOverVoltage");

        pt->addRowSeparator(tr("Balancing configuration"));
        pt->addParamRow(conf, "cellBalanceStart");
        pt->addParamRow(conf, "cellBalanceDifferenceThreshold");
        pt->addParamRow(conf, "cellBalanceUpdateInterval");

        pt->addRowSeparator(tr("SoC general"));
#if 0 // disable
        pt->addParamRow(conf, "stateOfChargeStoreInterval");
        pt->addParamRow(conf, "timeoutChargeCompleted");
        pt->addParamRow(conf, "timeoutChargingCompletedMinimalMismatch");
#endif
        pt->addParamRow(conf, "minimalPrechargePercentage"); // from pagemastersettings.cpp
        pt->addParamRow(conf, "timeoutLCPreCharge"); // from pagemastersettings.cpp

        pt->addRowSeparator(tr("Limits"));
        pt->addParamRow(conf, "maxMismatchThreshold");
        pt->addParamRow(conf, "maxAllowedCurrent");
#if 0
        pt->addParamRow(conf, "allowedTempBattDischargingMax");
        pt->addParamRow(conf, "allowedTempBattDischargingMin");
#endif
        pt->addParamRow(conf, "allowedTempBattChargingMax");
        pt->addParamRow(conf, "allowedTempBattChargingMin");

#if 0 // disable
        pt->addRowSeparator(tr("NTC specifications battery"));
        pt->addParamRow(mDieBieMS->bmsConfig(), "noOfTempSensorPerModule");
        pt->addParamRow(mDieBieMS->bmsConfig(), "NTCLTC25Deg");
        pt->addRowSeparator(tr("NTC specifications expansion Board"));
        pt->addParamRow(mDieBieMS->bmsConfig(), "noOfExpansionBoard");
        pt->addParamRow(mDieBieMS->bmsConfig(), "noOfTempSensorPerExpansionBoard");
#endif
    }
*/

}


/*
bool BmsSettings::addParamRow(QLineEdit* edit, ConfigParams *params, QString paramName)
{
    bool res = false;
    QWidget *editor = params->getEditor(paramName);
    QString name = params->getLongName(paramName);

    if (editor) {
        //int row = rowCount();
        //setRowCount(row + 1);
        //QTableWidgetItem *item = new QTableWidgetItem(name);
        //item->setFlags(item->flags() & ~Qt::ItemIsEditable);
        //setItem(row, 0, item);
        //setCellWidget(row, 1, editor);
        //edit->setText(editor->);

        auto vtype = editor->property("type");
        auto type = vtype.toInt();
        //CFG_T_UNDEFINED = 0,
        if(type == 1) // CFG_T_DOUBLE,
        {
            auto vval = editor->property("value");
            auto val = vval.toDouble();
            edit->setText(QString::number(val));
        }
        else if(type == 2) // CFG_T_INT,
        {
            auto vval = editor->property("value");
            auto val = vval.toInt();
            edit->setText(QString::number(val));
        }
        else if(type == 3) // CFG_T_QSTRING,
        {
            auto vval = editor->property("value");
            auto val = vval.toString();
            edit->setText(val);
        }
        else if(type == 4) // CFG_T_ENUM,
        {
            auto vval = editor->property("value");
            auto val = vval.toInt();
            edit->setText(QString::number(val));
        }
        else if(type == 5) // CFG_T_BOOL
        {
            auto vval = editor->property("value");
            auto val = vval.toBool();
            edit->setText(val ? "true" : "false");
        }

        auto vsuffix = editor->property("suffix");
        auto suffix = vsuffix.toString();
        auto veditorDecimalsDouble = editor->property("editorDecimalsDouble");
        auto editorDecimalsDouble = veditorDecimalsDouble.toDouble();
        auto veditAsPercentage = editor->property("editAsPercentage");
        auto editAsPercentage = veditAsPercentage.toBool();

        res = true;
        //resizeColumnToContents(0);
        //resizeRowsToContents();
    }

    return res;
}
*/


void BmsSettings::on_pbCalibrateZeroPoint_clicked()
{
    // setZeroCurrent to Terminal
    //emit sendMessage("setZeroCurrent");

    if ( mDieBieMS == nullptr ) {
        return;
    }

    if ( !mDieBieMS->isPortConnected() ) {
        QMessageBox::critical(this,
                              tr("Connection Error"),
                              tr("The ENNOID-BMS is not connected. Please connect it."));
        return;
    }

    mDieBieMS->commands()->sendTerminalCmd("setZeroCurrent");
    QTimer::singleShot(1000, [this](){
        this->mDieBieMS->commands()->sendTerminalCmd("config_write");
    });

}
/*
void BmsSettings::on_pbWriteIntoNonVolatileMemoryOfBsm_clicked()
{

}

void BmsSettings::on_pbWriteCurrentValuesIntoBsm_clicked()
{
}
*/
void BmsSettings::on_pbWriteToNonVolatileBmsMemory_clicked()
{
    // Записать в энергонезависимую\nпамять BMS
    // actionStoreBMScconf
    mDieBieMS->commands()->storeBMSConfig();
}

void BmsSettings::on_pbWriteCurrentValuesToBms_clicked()
{
    // Записать текущие значения в BMS
    // actionWriteBMScconf
    mDieBieMS->commands()->setBMSconf();
}


void BmsSettings::onSaveBMSConfToXmlFileClicked()
{
    QString path;
    path = QFileDialog::getSaveFileName(this,
                                        tr("Choose where to save the motor configuration XML file"),
                                        ".",
                                        tr("Xml files (*.xml)"));

    if (path.isNull()) {
        return;
    }

    if (!path.toLower().endsWith(".xml")) {
        path += ".xml";
    }

    bool res = mDieBieMS->bmsConfig()->saveXml(path, "bmsConfiguration");

    if (res) {
        emit showStatusInfo("Saved motor configuration", true);
    } else {
        emit showMessageDialog(tr("Save motor configuration"),
                          tr("Could not save motor configuration:<BR>"
                             "%1").arg(mDieBieMS->bmsConfig()->xmlStatus()),
                          false, false);
    }
}


void BmsSettings::onLoadBMSConfFromXmlFileClicked()
{
    QString path;
    path = QFileDialog::getOpenFileName(this,
                                        tr("Choose motor configuration file to load"),
                                        ".",
                                        tr("Xml files (*.xml)"));

    if (path.isNull()) {
        return;
    }

    bool res = mDieBieMS->bmsConfig()->loadXml(path, "bmsConfiguration");

    if (res) {
        emit showStatusInfo("Loaded motor configuration", true);
    } else {
        emit showMessageDialog(tr("Load motor configuration"),
                          tr("Could not load motor configuration:<BR>"
                             "%1").arg(mDieBieMS->bmsConfig()->xmlStatus()),
                          false, false);
    }
}
