#include "setregswindow.h"
#include "communication/messages.h"
#include "mainwindow.h"
#include "ui_setregswindow.h"

setRegsWindow::setRegsWindow(QWidget *parent)
    : QDialog(parent), ui(new Ui::setRegsWindow) {
  ui->setupUi(this);
  this->parent = parent;
}

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

void setRegsWindow::hexControl(const QString &text, QLineEdit *edit) {
  int pos = edit->cursorPosition();
  edit->setText(text.toUpper());
  edit->setCursorPosition(pos);
}

void setRegsWindow::on_readAddEdit_textChanged(const QString &arg1) {
  this->hexControl(arg1, this->ui->readAddEdit);
}

void setRegsWindow::on_writeAddEdit_textChanged(const QString &arg1) {
  this->hexControl(arg1, this->ui->writeAddEdit);
}

void setRegsWindow::on_writeValueEdit_textChanged(const QString &arg1) {
  this->hexControl(arg1, this->ui->writeValueEdit);
}

void setRegsWindow::on_readButton_clicked() {
  if (!this->ui->readAddEdit->text().isEmpty()) {
    bool bStatus = false;
    uint8_t add = static_cast<uint8_t>(
        this->ui->readAddEdit->text().toUInt(&bStatus, 16));
    readReg[3] = static_cast<char>(add);
    reinterpret_cast<MainWindow *>(this->parent)->getPort()->send(readReg);
  }
}

void setRegsWindow::on_writeButton_clicked() {
  if (!this->ui->writeAddEdit->text().isEmpty() &&
      !this->ui->writeValueEdit->text().isEmpty()) {
    bool bStatus = false;
    uint8_t add = static_cast<uint8_t>(
        this->ui->writeAddEdit->text().toUInt(&bStatus, 16));
    QString data = this->ui->writeValueEdit->text();
    data.replace(" ", "");
    uint16_t d = static_cast<uint16_t>(data.toUInt(&bStatus, 16));
    writeReg[3] = static_cast<char>(add);
    writeReg[4] = static_cast<char>(d);
    writeReg[5] = static_cast<char>(d >> 8);
    reinterpret_cast<MainWindow *>(this->parent)->getPort()->send(writeReg);
  }
}

void setRegsWindow::registerData(uint8_t add, uint16_t data) {
  QString address = QString::number(add, 16).toUpper();
  while (address.length() < 2) {
    address.prepend('0');
  }
  QString d = QString::number(data, 16).toUpper();
  while (d.length() < 4) {
    d.prepend('0');
  }
  this->ui->readAddEdit->setText(address);
  this->ui->readValueEdit->setText(d);
}

void setRegsWindow::portStatus(bool stat, bool previousStat) {
  if (stat && !previousStat) {
    // Opened
    this->ui->readButton->setEnabled(true);
    this->ui->writeButton->setEnabled(true);
  } else if (!stat && previousStat) {
    // Closed
    this->ui->readButton->setEnabled(false);
    this->ui->writeButton->setEnabled(false);
  }
}
