#include "renamedialog.h"

#include <QLabel>
#include <QKeyEvent>
#include <QPushButton>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <ukuistylehelper/ukuistylehelper.h>

RenameDialog::RenameDialog(const QString& originalName, QWidget *parent)
    : QDialog(parent), m_newName(originalName)
{
    setupUI(originalName);
}

void RenameDialog::setupUI(const QString& originalName) {
    this->setFixedSize(370, 200);
    kdk::UkuiStyleHelper::self()->removeHeader(this);

    m_closeBtn = new QPushButton;
    m_closeBtn->setFlat(true);
    m_closeBtn->setFixedSize(32, 32);
    m_closeBtn->setProperty("isWindowButton", 0x2);
    m_closeBtn->setProperty("useIconHighlightEffect", 0x8);
    m_closeBtn->setIcon(QIcon::fromTheme("window-close-symbolic"));
    m_closeBtn->setToolTip(tr("Close"));

    m_titleWidget = new QWidget();
    m_titleWidget->setFixedSize(370, 32);
    m_titleLayout = new QHBoxLayout(m_titleWidget);
    m_titleLayout->setContentsMargins(12, 0, 12, 0);
    m_titleLayout->addStretch();
    m_titleLayout->addWidget(m_closeBtn);
    m_titleLayout->setAlignment(Qt::AlignCenter);

    m_textLabel = new  QLabel(tr("Rename"));
    m_nameEdit = new QLineEdit(originalName);
    m_nameEdit->setFixedSize(322, 32);
    m_nameEdit->setObjectName("nameEdit");
    m_nameEdit->setStyleSheet("#nameEdit{border-radius:4px; border:2px;}");
    m_nameEdit->setTextMargins(8, 6, 8, 6);

    m_contentWidget = new QWidget();
    m_contentWidget->setContentsMargins(16, 0, 16, 0);
    m_contentLayout = new QVBoxLayout(m_contentWidget);
    m_contentLayout->setContentsMargins(0, 0, 0, 0);
    m_contentLayout->addWidget(m_textLabel);
    m_contentLayout->addWidget(m_nameEdit);

    m_cancelBtn = new QPushButton(tr("Cancel"), this);
    m_okBtn = new QPushButton(tr("Ok"), this);
    m_okBtn->setProperty("isImportant", true);
    m_cancelBtn->setFixedHeight(36);
    m_okBtn->setFixedHeight(36);
    m_btnLayout = new QHBoxLayout;
    m_btnLayout->setContentsMargins(16, 16, 16, 16);
    m_btnLayout->addStretch();
    m_btnLayout->addWidget(m_cancelBtn);
    m_btnLayout->addWidget(m_okBtn);

    m_vLayout = new QVBoxLayout(this);
    m_vLayout->addWidget(m_titleWidget);
    m_vLayout->addWidget(m_contentWidget);
    m_vLayout->addLayout(m_btnLayout);
    this->setLayout(m_vLayout);

    connect(m_closeBtn, &QPushButton::clicked, [&](){this->close();});
    connect(m_closeBtn, &QPushButton::clicked, this, &QDialog::reject);
    connect(m_okBtn, &QPushButton::clicked, this, &RenameDialog::accept);
}

QString RenameDialog::getNewName() const {
    return m_newName;
}

// 弹窗显示后按Esc关闭弹窗
void RenameDialog::keyPressEvent(QKeyEvent *event){
    if(event->key() == Qt::Key_Escape){
        this->window()->close();
    }
}

void RenameDialog::accept() {
    m_newName = m_nameEdit->text();
    QDialog::accept();
}
