//
// Created by 张雪明 <zhangxueming@uniontech.com> on 2024/11/22.
//
#include "ImmuFactoryRestoreWidget.h"
#include <DFontSizeManager>
#include <QRadioButton>
#include <DDialog>
#include <DWaterProgress>
#include <QDir>
#include <QDebug>
#include "common/radioitem.h"
#include "utils/Utils.h"

#if DTK_VERSION >= DTK_VERSION_CHECK(5, 5, 10, 0)
#include <DPaletteHelper>
#else
#include <DApplicationHelper>
#endif

ImmuFactoryRestoreWidget::ImmuFactoryRestoreWidget(QWidget* parent) : QWidget(parent)
{
    this->setAccessibleName("ImmuFactoryRestoreWidget");
    this->initUI();

    this->setFixedHeight(600);
}

void ImmuFactoryRestoreWidget::initUI()
{
    m_existInitBackup = this->isExistInitBackup();
    m_titleLabel = new QLabel();
    m_titleLabel->setText(tr("Reset to factory settings"));
    m_titleLabel->setAccessibleName("uosImmuResetToFactorySettings");
    m_titleLabel->setAlignment(Qt::AlignLeft);
    m_titleLabel->setFixedHeight(35);
    DFontSizeManager::instance()->bind(m_titleLabel, DFontSizeManager::T4);
    QFont font = m_titleLabel->font();
    font.setWeight(QFont::Bold);
    m_titleLabel->setFont(font);
    QPalette titlePalette;
    titlePalette.setColor(QPalette::BrightText, QColor(qRgba(0,0,0,0.85)));
    m_titleLabel->setPalette(titlePalette);

    m_restoreLabel = new QLabel();
    m_restoreLabel->setAccessibleName("uosImmuResetToFactorySettings_restoreLabel");
    m_restoreLabel->setPixmap(Utils::hidpiPixmap(":/resources/icons/v25/initialize_restore_v25.png", QSize(160, 160)));

    m_savaUserDataItem = new RadioItem();
    m_savaUserDataItem->setAccessibleName("uosImmuResetToFactorySettings_savaUserDataItem");
    m_savaUserDataItem->radioButton()->setChecked(true);
    m_savaUserDataItem->setTitle(tr("Keep personal files and apps"));
    m_savaUserDataItem->setRadioButtonAccessibleName("uosImmuResetToFactorySettings_savaUserDataItemRadioButton");
    QPalette savaUserDataPalette;
    savaUserDataPalette.setColor(QPalette::BrightText, QColor(qRgba(0,0,0,0.7)));
    m_savaUserDataItem->setPalette(savaUserDataPalette);
    QFont savaUserDataFont = m_savaUserDataItem->font();
    savaUserDataFont.setWeight(QFont::Medium);
    m_savaUserDataItem->setFont(savaUserDataFont);
    DFontSizeManager::instance()->bind(m_savaUserDataItem, DFontSizeManager::T6);
    m_savaUserDataItem->radioButton()->setDisabled(true);

    m_descriptionLabel = new DTipLabel();
    m_descriptionLabel->setText(tr("Restore your system to the initial installation state"));
    m_descriptionLabel->setAccessibleName("ResetToFactorySettings_DescriptionLabel");

    m_descriptionLabel->setForegroundRole(DPalette::PlaceholderText);
    DFontSizeManager::instance()->bind(m_descriptionLabel, DFontSizeManager::T6);
   

    m_tipsLabel = new DTipLabel();
    m_tipsLabel->setWordWrap(true);
    m_descriptionLabel->setAccessibleName("ResetToFactorySettings_TipsLabel");
//    auto pa = DApplicationHelper::instance()->palette(m_tipsLabel);
#if DTK_VERSION >= DTK_VERSION_CHECK(5, 5, 10, 0)
    DPalette pa = DPaletteHelper::instance()->palette(m_tipsLabel);
#else
    DPalette pa = DApplicationHelper::instance()->palette(m_tipsLabel);
#endif
    pa.setBrush(DPalette::TextTips, Qt::red);
#if DTK_VERSION >= DTK_VERSION_CHECK(5, 5, 10, 0)
    DPaletteHelper::instance()->setPalette(m_tipsLabel, pa);
#else
    DApplicationHelper::instance()->setPalette(m_tipsLabel, pa);
#endif

    m_tipsLabel->hide();

    m_loadingWidget = new QWidget();
    m_loadingWidget->setAccessibleName("ResetToFactorySettings_loadingWidget");
    m_loadingWidget->setVisible(false);

    QVBoxLayout* loadingLayout = new QVBoxLayout;
    m_loadingWidget->setLayout(loadingLayout);

    DWaterProgress* loadingIndicator = new DWaterProgress;
    loadingIndicator->setAccessibleName("ResetToFactorySettings_DWaterProgress");
    loadingLayout->addWidget(loadingIndicator, 0, Qt::AlignHCenter);
    loadingIndicator->setValue(50);
    loadingIndicator->setTextVisible(false);
    loadingIndicator->setFixedSize(48, 48);
    loadingIndicator->start();

    QLabel* tips = new QLabel(tr("Applying changes to your system..."));
    tips->setAccessibleName("ResetToFactorySettings_ApplyingTipsLabel");
    loadingLayout->addWidget(tips);

    m_startRestoreBtn = new DPushButton();
    m_startRestoreBtn->setAccessibleName("uosImmuResetToFactorySettings_startRestoreBtn");
    m_startRestoreBtn->setText(tr("Start Restore"));
    m_startRestoreBtn->setFixedSize(200, 36);
    m_startRestoreBtn->setAccessibleName("ResetToFactorySettings_StartRestore");
    // QPalette startRestorePalette;
    // startRestorePalette.setColor(QPalette::ButtonText, QColor(qRgb(0,88,222)));
    // m_startRestoreBtn->setPalette(startRestorePalette);
    // m_startRestoreBtn->setForegroundRole(QPalette::ButtonText);

    if (!m_existInitBackup) {
        m_tipsLabel->setVisible(true);
        m_tipsLabel->setText(tr("The initial backup file does not exist, so your system cannot be reset to factory settings."));

        m_savaUserDataItem->setEnabled(false);
        m_startRestoreBtn->setEnabled(false);
        m_descriptionLabel->setEnabled(false);
    }

    m_mainLayout = new QVBoxLayout;
    m_mainLayout->setContentsMargins(0, 8, 0, 28);
    auto titleLayout = new QHBoxLayout;
    titleLayout->addSpacing(12);
    titleLayout->addWidget(m_titleLabel);
    m_mainLayout->addLayout(titleLayout);
    m_mainLayout->addSpacing(110);
    m_mainLayout->addWidget(m_restoreLabel, 0, Qt::AlignHCenter);
    m_mainLayout->addWidget(m_descriptionLabel, 0, Qt::AlignHCenter);
    m_mainLayout->addSpacing(24);
    m_mainLayout->addWidget(m_tipsLabel);
    m_mainLayout->addWidget(m_loadingWidget, 0, Qt::AlignCenter);

    auto startBtnLayout = new QHBoxLayout;
    startBtnLayout->addWidget(m_startRestoreBtn, 0, Qt::AlignHCenter);
    m_mainLayout->addLayout(startBtnLayout);
    m_mainLayout->addStretch();
    setLayout(m_mainLayout);

    connect(m_startRestoreBtn, &DPushButton::clicked, this, &ImmuFactoryRestoreWidget::startRestore, Qt::QueuedConnection);
}

bool ImmuFactoryRestoreWidget::isExistInitBackup()
{
    return true;
}

void ImmuFactoryRestoreWidget::startRestore()
{
    Q_EMIT immuFactoryRestoreClicked();
}

int ImmuFactoryRestoreWidget::showFactoryRestoreTips()
{
    bool formatData = !(m_savaUserDataItem->radioButton()->isChecked());
    m_tipsLabel->setVisible(false);
    m_tipsLabel->setText("");

    DDialog dialog(this);
    dialog.setIcon(QIcon::fromTheme("dialog-warning"));

    if (formatData) {
        dialog.setFixedSize(450, 240);
        dialog.setTitle(tr("Reset to Factory Settings"));
        dialog.setMessage(tr("It will permanently clear data of all users on this device, please confirm before proceeding"));
    } else {
        dialog.setTitle(tr("Keep Personal Files"));
        QString msg = tr("It will reset data on your system disk but keep your personal data. You need to create an account with the same username as the current user so that you can access your personal data later. Please confirm before proceeding.");
        int msgSize = msg.length();
        int minSize = 11; // 控制中心最小字号是11
        int normalMaxFontHeight = 31; // 控制中心字号20，对应的中文的字体高度
        QFont font = dialog.font();
        QFontMetrics fontMetrics(font);
        int fontSize = font.pointSize();
        int diffHeight = fontMetrics.height() - normalMaxFontHeight;
        // msgSize diffHeight 来调整藏语等翻译后文案比较长，字体高度比较高
        int width = 420 + (fontSize - minSize) * 10 + diffHeight * 5 + (msgSize < 100 ? 0 : 50);
        int height = 230 + (fontSize - minSize) * 10 + (diffHeight <= 0 ? diffHeight : diffHeight * 4) + (msgSize < 100 ? 0 : 60);
        dialog.setFixedSize(width, height);
        dialog.setMessage(msg);
    }

    dialog.addButton(tr("Cancel", "button"));
    QRect rect = geometry();
    dialog.move(rect.center());
    dialog.moveToCenter();

    int result = dialog.addButton(tr("Confirm and Reset"), true, DDialog::ButtonWarning);
    dialog.setAccessibleName("ImmuFactoryRestoreWidget_WarningDialog");
    dialog.getButton(0)->setAccessibleName("ImmuFactoryRestoreWidget_Cancel");
    dialog.getButton(1)->setAccessibleName("ImmuFactoryRestoreWidget_ConfirmAndReset");
    if (dialog.exec() != result) {
        return -1;
    }

    m_savaUserDataItem->setEnabled(false);

    return 0;
}

void ImmuFactoryRestoreWidget::doSuccess()
{
    int result = -1;
    DDialog dialog(this);
    dialog.setIcon(QIcon::fromTheme("dialog-warning"));
    dialog.addButton(tr("Cancel", "button"));
    dialog.setMessage(tr("System restore is ready. Do you want to reboot and restore your system now?"));
    result = dialog.addButton(tr("Reboot and Restore"), true, DDialog::ButtonWarning);
    QRect rect = geometry();
    dialog.move(rect.center());
    dialog.moveToCenter();
    dialog.setAccessibleName("ImmuFactoryRestoreWidget_doSuccessDialog");
    dialog.getButton(0)->setAccessibleName("ImmuFactoryRestoreWidget_doSuccessDialogCancel");
    dialog.getButton(1)->setAccessibleName("ImmuFactoryRestoreWidget_doSuccessDialogRebootAndRestore");

    if (dialog.exec() != result) {
        return;
    }

    qDebug() << Q_FUNC_INFO <<", ImmuFactoryRestoreWidget::doSuccess reboot now";
    Utils::reboot(true, false);
}

void ImmuFactoryRestoreWidget::doError(int errCode)
{
    m_startRestoreBtn->setVisible(true);
    m_tipsLabel->setVisible(true);
    if (nullptr != m_savaUserDataItem) {
        m_savaUserDataItem->setEnabled(true);
    }

    ErrorType type = static_cast<ErrorType>(errCode);
    switch (type) {
        case ErrorType::PathError: {
            m_tipsLabel->setText(tr("Invalid path"));
            break;
        }
        default: {
            m_tipsLabel->setVisible(false);
            break;
        }
    }
}

void ImmuFactoryRestoreWidget::setTipsVisible(const bool &visible)
{
    if (nullptr != m_tipsLabel) {
        m_tipsLabel->setVisible(visible);
    }
}

void ImmuFactoryRestoreWidget::setTipsLabelText(const QString &msg)
{
    if (nullptr != m_tipsLabel) {
        m_tipsLabel->setText(msg);
    }
}

void ImmuFactoryRestoreWidget::setRestartBtnVisible(bool visible)
{
    if (nullptr != m_startRestoreBtn) {
        m_startRestoreBtn->setVisible(visible);
    }
}
