#include "verificationwidget.h"

#include "ui_verificationwidget.h"

#include "../colouredlineedit/colouredlineedit.h"

#include <QDebug>

VerificationWidget::VerificationWidget(QWidget *parent, LineEditFlag flags)
    : QWidget(parent), m_inputVerified(false),
      m_ui(new Ui::VerificationWidget) {
  m_ui->setupUi(this);
  createWidgets();
  configureConnections();
  setLineEditFlags(flags);
}

VerificationWidget::~VerificationWidget() { delete m_ui; }

void VerificationWidget::createWidgets() {
  m_lineEdit = new ColouredLineEdit;
  m_ui->m_mainLayout->addWidget(m_lineEdit);
}

void VerificationWidget::configureConnections() {
  connect(m_lineEdit, &QLineEdit::textEdited, this,
          &VerificationWidget::checkWithEmit);
}

void VerificationWidget::setReference(const QString &value) {
  m_ui->m_referenceValueLabel->setText(value);
}

void VerificationWidget::setOldValueEnterText(const QString &value) {
  m_ui->m_oldValueEnterLabel->setText(value);
}

void VerificationWidget::setFocus() { m_lineEdit->setFocus(); }

void VerificationWidget::noticeRed() { m_lineEdit->notice(Qt::red); }

void VerificationWidget::setLineEditFlags(LineEditFlag flags) {
  m_lineEditFlags = flags;
  m_luminousInvalidInput = m_lastLineEditFlag & LuminousAcceptableInput;
}

bool VerificationWidget::checkWithEmit() {
  const QString &reference = m_ui->m_referenceValueLabel->text();
  const QString &oldValue = m_lineEdit->text();
  m_inputVerified = !reference.isNull() && reference == oldValue;
  handleLineEditClassFlags(m_inputVerified);
  emit benchmarkMatching(m_inputVerified);
  return m_inputVerified;
}

void VerificationWidget::handleLineEditClassFlags(bool check) {
  int mask = m_lastLineEditFlag;
  while (mask > 0x00) {
    if (m_lineEditFlags & mask)
      switch (mask) {
      case LineEditFlag::LockOnCorrectInput: {
        if (check != true)
          break;
        m_lineEdit->clearFocus();
        m_lineEdit->setDisabled(true);
      } break;
      case LineEditFlag::NoticeOnAcceptableInput: {
        if (check != true)
          break;
        m_lineEdit->notice(QColor(0xA0EF95), m_luminousAcceptableInput);
      } break;
      default:
        break;
      }
    mask >>= 1;
  }
}

bool VerificationWidget::inputVerified() { return m_inputVerified; }
