#include "TedsWriterMemTest.h"
#include "ui_TedsWriterMemTest.h"
#include "Device/TedsWriterDevice.h"
#include "LQError.h"
#include <QMessageBox>

TedsWriterMemTest::TedsWriterMemTest(QWidget *parent) :
    TedsWriterDevBaseWidget{parent},
    m_ui{new Ui::TedsWriterMemTest} {
    m_ui->setupUi(this);

    m_validator.setRegExp(QRegExp(QStringLiteral("(\\d|[A-F]|[a-f]){256}")));

    connect(m_ui->writeBtn, &QPushButton::clicked, this, &TedsWriterMemTest::write);
    connect(m_ui->readBtn, &QPushButton::clicked, this, &TedsWriterMemTest::read);
    connect(m_ui->text, &QPlainTextEdit::textChanged, this, &TedsWriterMemTest::checkText);
    setEnabled(false);
}

TedsWriterMemTest::~TedsWriterMemTest() {

}

void TedsWriterMemTest::memStateUpdate(bool connected) {
    setEnabled(connected);
    if (connected) {
        read();
    }
}

void TedsWriterMemTest::read() {
    LQError err;
    QByteArray data;
    device().readTedsData(0, 128, data, err);
    if (err.isSuccess()) {
        QString text;
        for (char byte : qAsConst(data)) {
            text += QString("%1").arg(static_cast<uint8_t>(byte), 2, 16, QChar('0'));
        }
        m_ui->text->setPlainText(text);
    } else {
        QMessageBox::critical(this, tr("Ошибка чтения памяти"), tr("Не удалось прочитать данные из TEDS-памяти: %1").arg(err.msg()));
    }
}

void TedsWriterMemTest::write() {
    LQError err;
    QString text = m_ui->text->toPlainText().toLower();


    QByteArray wrArray;
    QByteArray curByteNibbles;
    for (const QChar ch : qAsConst(text)) {

        if ((ch >= '0' && ch <= '9')) {
            curByteNibbles.append((ch.toLatin1() - '0'));
        } else if ((ch >= 'a') && (ch <= 'f')) {
            curByteNibbles.append((ch.toLatin1() - 'a' + 10));
        } else {
            curByteNibbles.clear();
        }

        if (curByteNibbles.size() == 2) {
            quint8 byte = (static_cast<quint8>(curByteNibbles.at(0)) << 4) | curByteNibbles.at(1);
            wrArray.append(byte);
            curByteNibbles.clear();
        }
    }

    while (wrArray.size() < 128) {
        wrArray.append(0xFF);
    }




    device().writeTedsData(0, wrArray, err);
    if (err.isSuccess()) {
        QMessageBox::information(this, tr("Запись данных"), tr("Запись данных в TEDS-память выполнена успешно"));
    } else {
        QMessageBox::critical(this, tr("Ошибка записи данных"), tr("Не удалось выполнить запись данных в TEDS-память: %1").arg(err.msg()));
    }
}

void TedsWriterMemTest::checkText() {
    QString curText {m_ui->text->toPlainText()};
    int pos {0};
    bool ok = m_validator.validate(curText, pos) == QValidator::State::Acceptable;
    if (ok) {
        m_ui->text->setStyleSheet(QStringLiteral("QPlainTextEdit { color: darkGreen }"));
    } else {
        m_ui->text->setStyleSheet(QStringLiteral("QPlainTextEdit { color: darkRed }"));
    }
    m_ui->writeBtn->setEnabled(ok);
}
