#include "dimFileRestoreWidget.h"
#include "utils/Utils.h"
#include "utils/global.h"
#include <QFileDialog>
#include <QLabel>
#include <QVBoxLayout>

dimFileRestoreWidget::dimFileRestoreWidget(DWidget *parent)
    : DWidget(parent)
{
    this->setAccessibleName("dimFileRestoreWidget");

    // 主题变换
    m_guiHelper = Dtk::Gui::DGuiApplicationHelper::instance();
    connect(m_guiHelper, &Dtk::Gui::DGuiApplicationHelper::themeTypeChanged, this, &dimFileRestoreWidget::onThemeChange);

    // 初始化UI
    initUI();
    initConnect();
    onThemeChange();
}

void dimFileRestoreWidget::initUI()
{
    QVBoxLayout *mainLayout = new QVBoxLayout;
    mainLayout->setContentsMargins(0, 0, 0, 0);

    // 初始化主标题和副标题
    m_title = new DLabel;
    m_title->setText(tr("Other Ways"));
    m_title->setAccessibleName("uosOtherWays_OtherWaysTitle");
    m_title->setAlignment(Qt::AlignHCenter);
    DFontSizeManager::instance()->bind(m_title, DFontSizeManager::T4);
    QFont font = m_title->font();
    font.setWeight(QFont::Bold);
    m_title->setFont(font);
    m_subTitle = new DLabel;
    m_subTitle->setText(tr("Select the system backup of UnionTech OS 20"));
    m_subTitle->setAccessibleName("uosOtherWays_OtherWaysSubTitle");

    mainLayout->addWidget(m_title, 0, Qt::AlignHCenter);
    mainLayout->addWidget(m_subTitle, 0, Qt::AlignHCenter);

    // 添加选择镜像保存目录组件
    m_selectPathWidget = new QWidget;
    QVBoxLayout *selectPathLayout = new QVBoxLayout;
    QLabel *imgPic = new QLabel;
    imgPic->setAlignment(Qt::AlignHCenter);
    imgPic->setAccessibleName("uosOtherWays_FileManagerLabel");
    imgPic->setPixmap(Utils::hidpiPixmap(":/resources/icons/file_manager.svg", QSize(96, 96)));
    m_destPathLabel = new DLabel;
    m_destPathLabel->setAccessibleName("uosOtherWays_DestPathLabel");
    m_destPathLabel->hide();
    m_fileSizeLabel = new DLabel;
    m_fileSizeLabel->hide();
    m_selectPath = new DPushButton;
    m_selectPath->setText(tr("Select a directory"));
    m_selectPath->setAccessibleName("uosOtherWays_SelectFile");
    m_selectPath->setStyleSheet("QPushButton {"
                                "color: #0081FF;"
                                "border: none;"
                                "background-color: transparent;"
                                "}");
    selectPathLayout->addWidget(imgPic, 0, Qt::AlignHCenter);
    selectPathLayout->addWidget(m_destPathLabel, 0, Qt::AlignHCenter);
    selectPathLayout->addWidget(m_fileSizeLabel, 0, Qt::AlignHCenter);
    selectPathLayout->addWidget(m_selectPath, 0, Qt::AlignHCenter);
    m_selectPathWidget->setLayout(selectPathLayout);

    m_calculateTip = new DSpinner;
    m_calculateTip->setAccessibleName("uosOtherWays_DSpinner");
    m_calculateTip->hide();
    m_calculateTip->setFixedSize(16, 16);
    m_calculateTip->setFocusPolicy(Qt::NoFocus);
    m_errorInfoLabel = new DLabel;
    m_errorInfoLabel->setText(tr("Attention: Your current system will be restored. Please proceed carefully!"));
    m_errorInfoLabel->setAccessibleName("uosOtherWays_ErrorInfoLabel");
    m_errorInfoLabel->setStyleSheet("QLabel {"
                                    "color: #FF0000;"
                                    "border: none;"
                                    "background-color: transparent;"
                                    "}");

    QHBoxLayout *calculateTipLayout = new QHBoxLayout();
    calculateTipLayout->setSpacing(10);
    calculateTipLayout->setContentsMargins(0,0,0,0);
    calculateTipLayout->addStretch();
    calculateTipLayout->addWidget(m_calculateTip);
    calculateTipLayout->addWidget(m_errorInfoLabel);
    calculateTipLayout->addStretch();
    QWidget *calculateTipWidget = new QWidget;
    calculateTipWidget->setFixedHeight(36);
    calculateTipWidget->setLayout(calculateTipLayout);

    // 初始化按钮控件
    m_cancel = new DPushButton;
    m_cancel->setFixedSize(140,36);
    m_cancel->setText(::QObject::tr("Cancel", "button"));
    m_cancel->setAccessibleName("uosOtherWays_Cancel");
    m_startRestore = new DSuggestButton;
    m_startRestore->setFixedSize(140, 36);
    m_startRestore->setText(::QObject::tr("Start Restore"));
    m_startRestore->setEnabled(false);
    m_startRestore->setAccessibleName("uosOtherWays_Restore");
    QHBoxLayout *buttonsLayout = new QHBoxLayout;
    buttonsLayout->setSpacing(10);
    buttonsLayout->addStretch();
    buttonsLayout->addWidget(m_cancel);
    buttonsLayout->addWidget(m_startRestore);
    buttonsLayout->addStretch();

    mainLayout->addStretch();
    mainLayout->addWidget(m_selectPathWidget, 0, Qt::AlignHCenter);
    mainLayout->addStretch();
    mainLayout->addStretch();
    mainLayout->addWidget(calculateTipWidget, 0, Qt::AlignHCenter);
    mainLayout->addLayout(buttonsLayout);
    setLayout(mainLayout);
}

void dimFileRestoreWidget::initConnect()
{
    connect(m_selectPath,   &DPushButton::clicked, this, &dimFileRestoreWidget::onSelectPathBtnClicked);
    connect(m_cancel,       &DPushButton::clicked, this, &dimFileRestoreWidget::cancelBtnSignal);
    connect(m_startRestore, &DSuggestButton::clicked, this, &dimFileRestoreWidget::startDimRestoreBtnClicked);
}

void dimFileRestoreWidget::setDestPath(const QString &destPath)
{
    if (destPath.isEmpty()) {
        m_destPathLabel->setText("");
        m_destPathLabel->hide();
        m_fileSizeLabel->setText("");
        m_fileSizeLabel->hide();
        m_startRestore->setEnabled(false);
        m_selectPath->setText(tr("Select a directory"));
        m_selectPath->setAccessibleName("uosOtherWays_SelectFile");
    } else {
        QDir srcDir(destPath);
        QStringList fileNames = {"*.dim"};
        QFileInfoList dimFileInfos = srcDir.entryInfoList(fileNames, QDir::Files | QDir::Readable, QDir::Name);

        if (dimFileInfos.size() > 0) {
            qint64 fileTotalSize = 0;
            for (QFileInfo item : dimFileInfos) {
                fileTotalSize += item.size();
            }
            double fileTotalSizeDouble = fileTotalSize * 1.0 / GiB;
            QString fileTotalSizeStr = QString("%1 : %2G").arg(tr("Backup file size")).arg(QString::number(fileTotalSizeDouble,'f',0));

            QFontMetrics fontWidth(m_destPathLabel->font());
            QString elideNote = fontWidth.elidedText(destPath, Qt::ElideMiddle, m_destPathLabel->width(), Qt::AlignLeft | Qt::AlignBottom | Qt::TextSingleLine);
            m_destPathLabel->setText(elideNote);
            (elideNote.indexOf("…") != -1) ? m_destPathLabel->setToolTip(destPath) : m_destPathLabel->setToolTip("");
            m_destPathLabel->show();

            m_fileSizeLabel->setText(fileTotalSizeStr);
            m_fileSizeLabel->show();
            m_startRestore->setEnabled(true);
            m_selectPath->setText(tr("Reselect a directory"));
            m_selectPath->setAccessibleName("uosOtherWays_ReselectFile");
        }
    }
}

void dimFileRestoreWidget::startCalculateTip(bool start, const QString &tipInfo)
{
    if (start) {
        m_calculateTip->start();
        m_calculateTip->show();
        m_selectPath->setEnabled(false);
        m_cancel->setEnabled(false);
        m_startRestore->setEnabled(false);

        m_errorInfoLabel->setText(tipInfo);
        QLabel styleLabel;
        m_errorInfoLabel->setStyleSheet(styleLabel.styleSheet());
        m_errorInfoLabel->show();

    } else {
        m_calculateTip->hide();
        m_calculateTip->stop();
        m_selectPath->setEnabled(true);
        m_cancel->setEnabled(true);
        m_startRestore->setEnabled(true);

        if (tipInfo.isEmpty()) {
            m_errorInfoLabel->setText(tr("Attention: Your current system will be restored. Please proceed carefully!"));
        } else {
            m_errorInfoLabel->setText(tipInfo);
        }
        m_errorInfoLabel->setStyleSheet("QLabel {"
                                        "color: #FF0000;"
                                        "border: none;"
                                        "background-color: transparent;"
                                        "}");
        m_errorInfoLabel->show();
    }
}

void dimFileRestoreWidget::startDimRestoreBtnClicked()
{
    QString destDir = (m_destPathLabel->text().indexOf("…") != -1) ? m_destPathLabel->toolTip() : m_destPathLabel->text();
    Q_EMIT startDimRestoreSignal(destDir);
}

void dimFileRestoreWidget::onSelectPathBtnClicked()
{
    QString srcDirStr = QFileDialog::getExistingDirectory(this->parentWidget(),"", "", QFileDialog::ReadOnly);
    if (srcDirStr.isEmpty()) {
        return;
    }

    setDestPath(srcDirStr);
}

void dimFileRestoreWidget::onThemeChange()
{

}

void dimFileRestoreWidget::setErrorTips(const QString &tips)
{
    if (m_errorInfoLabel != nullptr) {
        m_errorInfoLabel->setText(tips);
    }
}
