#include "NameInputDialog.h"

#include <QHBoxLayout>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QVBoxLayout>

namespace
{
    const int kSpacingPx        = 8;
    const int kMinimumWidthPx = 280;
}

NameInputDialog::NameInputDialog(const QString& title, const QString& prompt,
                                 QWidget* parent)
    : ModalDialog(parent)
    , m_nameEdit(nullptr)
{
    QVBoxLayout* mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(kSpacingPx, kSpacingPx, kSpacingPx, kSpacingPx);
    mainLayout->setSpacing(kSpacingPx);

    QLabel* promptLabel = new QLabel(prompt, this);
    mainLayout->addWidget(promptLabel);

    m_nameEdit = new QLineEdit(this);
    m_nameEdit->setMinimumWidth(kMinimumWidthPx);
    mainLayout->addWidget(m_nameEdit);

    QHBoxLayout* buttonLayout = new QHBoxLayout();
    buttonLayout->setSpacing(kSpacingPx);
    buttonLayout->addStretch();

    QPushButton* confirmButton = new QPushButton(tr("Confirm"), this);
    QPushButton* cancelButton  = new QPushButton(tr("Cancel"), this);
    buttonLayout->addWidget(confirmButton);
    buttonLayout->addWidget(cancelButton);
    mainLayout->addLayout(buttonLayout);

    connect(confirmButton, &QPushButton::clicked, this, &QDialog::accept);
    connect(cancelButton,  &QPushButton::clicked, this, &QDialog::reject);
    // Enter confirms from the line edit, as it did in the prompt this replaces.
    connect(m_nameEdit, &QLineEdit::returnPressed, this, &QDialog::accept);

    addHeader(mainLayout, title, false);

    // The line edit is what the player came here to use, and it takes Q as a character
    // because it holds the focus (REQ-UI-DIALOG-DISMISS). Set here for a dialog shown on
    // its own, and named again through getInitialFocusWidget() for the usual case: being
    // hosted on the modal layer reparents this dialog, which clears the focus set here.
    m_nameEdit->setFocus();
}

QWidget* NameInputDialog::getInitialFocusWidget() const
{
    return m_nameEdit;
}

QString NameInputDialog::getName() const
{
    return m_nameEdit->text().trimmed();
}
