#include "renamedialog.h"

#include "ui_renamedialog.h"

#include "../verificationwidget/verificationwidget.h"

#include <QToolTip>

#include <QDebug>

void RenameDialog::done(int resultCode) {
  if (QDialog::Accepted == resultCode) {
    if (m_verificationWidget->inputVerified() == false) {
      m_verificationWidget->noticeRed();
      m_verificationWidget->setFocus();
      QApplication::beep();
      return;
    } else {
      auto newValue = m_ui->m_newValueLineEdit->text().trimmed();
      m_ui->m_newValueLineEdit->setText(newValue);
      if (newValue.isEmpty()) {
        QString errorString(tr("No text is unacceptable"));
        QSize frameSize = m_ui->m_newValueLineEdit->frameSize();
        QPoint point(frameSize.width() / 2.5, -frameSize.height() * 1.5);
        QToolTip::showText(m_ui->m_newValueLineEdit->mapToGlobal(point),
                           errorString);
        QApplication::beep();
        return;
      }
    }
  }
  QDialog::done(resultCode);
  return;
}

RenameDialog::RenameDialog(const QString &reference, QWidget *parent,
                           Qt::WindowFlags f)
    : QDialog(parent, f), m_ui(new Ui::RenameDialog) {
  m_ui->setupUi(this);
  setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
  createWidgets();
  configureConnections();
  setReference(reference);
}

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

void RenameDialog::createWidgets() {
  m_verificationWidget = new VerificationWidget;
  m_ui->m_verificationLayout->addWidget(m_verificationWidget);
  m_verificationWidget->setFocus();
}

void RenameDialog::configureConnections() {
  connect(m_verificationWidget, &VerificationWidget::benchmarkMatching, this,
          &RenameDialog::toggleLineEditFocus);
}

void RenameDialog::toggleLineEditFocus(bool checkPassed) {
  if (!checkPassed)
    return;
  m_ui->m_newValueLineEdit->setEnabled(true);
  m_ui->m_newValueLineEdit->setFocus();
}

void RenameDialog::setReference(const QString &reference) {
  m_verificationWidget->setReference(reference);
}

void RenameDialog::setTopText(const QString &value) {
  m_ui->m_topLabel->setText(value);
}

QString RenameDialog::newValue() { return m_ui->m_newValueLineEdit->text(); }
