#include "settingsdialog.h"
#include "ui_settingsdialog.h"

SettingsDialog::SettingsDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::SettingsDialog)
{
    ui->setupUi(this);
    ui->parityCombo->setCurrentIndex(0);
#if QT_CONFIG(modbus_serialport)
    ui->baudCombo->setCurrentText(QString::number(m_settings.baud));
    ui->dataBitsCombo->setCurrentText(QString::number(m_settings.dataBits));
    ui->stopBitsCombo->setCurrentText(QString::number(m_settings.stopBits));
    on_updateComBox_clicked();
#endif
    ui->timeoutSpinner->setValue(m_settings.responseTime);
    ui->retriesSpinner->setValue(m_settings.numberOfRetries);
    connect(ui->AcceptOrRejectButtonBox, &QDialogButtonBox::accepted, [this]() {
#if QT_CONFIG(modbus_serialport)
        m_settings.portName = ui->comBox->currentData().toString();
        m_settings.parity = ui->parityCombo->currentIndex();
        if (m_settings.parity > 0)
            m_settings.parity++;
        m_settings.baud = ui->baudCombo->currentText().toInt();
        m_settings.dataBits = ui->dataBitsCombo->currentText().toInt();
        m_settings.stopBits = ui->stopBitsCombo->currentText().toInt();
#endif
        m_settings.responseTime = ui->timeoutSpinner->value();
        m_settings.numberOfRetries = ui->retriesSpinner->value();
        hide();
    });
}

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

SettingsDialog::Settings SettingsDialog::settings() const
{
    return m_settings;
}

int SettingsDialog::UpdateBaud(int baud)
{
    ui->baudCombo->setCurrentIndex(baud);
    return (m_settings.baud = ui->baudCombo->currentText().toInt());
}

int SettingsDialog::UpdateParity(int parity)
{
    ui->parityCombo->setCurrentIndex(parity);
    if(parity>0) {
        return  (m_settings.parity = ++parity);
    } else {
        return (m_settings.parity = parity);
    }
}

int SettingsDialog::curBaud()
{
    return ui->baudCombo->currentIndex();
}

int SettingsDialog::curParity()
{
    return ui->parityCombo->currentIndex();
}

void SettingsDialog::on_updateComBox_clicked()
{
    ui->comBox->clear();
    const auto listPorts = QSerialPortInfo::availablePorts();
    for (const auto& port: listPorts) {
        ui->comBox->addItem(QString(port.portName() + ": " + port.manufacturer()), QVariant(port.portName()));
    }
}
