#include "settingsextrapage.h"
#include "ui_settingsextrapage.h"

#include <QIntValidator>
#include <QDoubleValidator>
#include <QDateTime>
#include <math.h>

//#include "configparamsgetter.h"
#include "connectandenterpage.h"

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

    // Коэффициент размера интерфейса:
    if (mSettings.contains("app_scale_factor")) {
        ui->uiScaleBox->setValue(mSettings.value("app_scale_factor").toDouble());
    }
    if (mSettings.contains("app_scale_auto")) {
        ui->uiAutoScaleBox->setChecked(mSettings.value("app_scale_auto").toBool());
    }
    ui->uiScaleBox->setEnabled(!ui->uiAutoScaleBox->isChecked());

    // Подключение:
    on_pbSerialRefreshButton_clicked();
}

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

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

void SettingsExtraPage::setDieBieMS(BMSInterface *dieBieMS)
{
    mDieBieMS = dieBieMS;

    if (mDieBieMS) {
        //connect(mDieBieMS->commands(), &Commands::valuesReceived,this, &SettingsExtraPage::valuesReceived);
        //connect(mDieBieMS->commands(), &Commands::cellsReceived,this, &VisualizationPage::cellsReceived);
    }
}


void SettingsExtraPage::on_uiScaleBox_valueChanged(double arg1)
{
    mSettings.setValue("app_scale_factor", arg1);
}

void SettingsExtraPage::on_uiAutoScaleBox_toggled(bool checked)
{
    mSettings.setValue("app_scale_auto", checked);
    ui->uiScaleBox->setEnabled(!checked);
}


void SettingsExtraPage::on_pbSerialRefreshButton_clicked()
{
    if (mDieBieMS) {
        ui->cboxComConnections->clear();
        QList<VSerialInfo_t> ports = mDieBieMS->listSerialPorts();
        foreach(const VSerialInfo_t &port, ports) {
            ui->cboxComConnections->addItem(port.name, port.systemPath);
        }
        ui->cboxComConnections->setCurrentIndex(0);
    }
}

void SettingsExtraPage::on_pbConnect_clicked()
{
    bool isConnected = false;
    if (mDieBieMS) {
        isConnected = mDieBieMS->connectSerial(ui->cboxComConnections->currentData().toString(),
                             ConnectAndEnterPage::SERIAL_BAUD_DEFAULT_VAL);
    }

    if(isConnected)
        emit connected();
    else
        emit disconnected();
}

void SettingsExtraPage::on_pbDisconnect_clicked()
{
    if (mDieBieMS) {
        mDieBieMS->disconnectPort();
    }

    emit disconnected();
}



