//
// Created by uos on 2022/3/28.
//

#include "utils/Utils.h"
#include "utils/global.h"
#include "SystemBackupWidget.h"
#include <QVBoxLayout>
#include <DFontSizeManager>


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

    // 主题变换
    m_guiHelper = Dtk::Gui::DGuiApplicationHelper::instance();
    connect(m_guiHelper, &Dtk::Gui::DGuiApplicationHelper::themeTypeChanged, this, &SystemBackupWidget::onThemeChange);
    // 初始化UI
    initUI();
    onThemeChange();
}

void SystemBackupWidget::initUI()
{
    QVBoxLayout *verticalLayout = new QVBoxLayout(this);
    verticalLayout->setContentsMargins(0, 20, 0, 10);
    verticalLayout->setAlignment(Qt::AlignHCenter);

    DLabel *title = new DLabel;
    title->setText(tr("System backup"));
    title->setAccessibleName("uosBackup_SystemBackupLabel");
    title->setAlignment(Qt::AlignCenter);
    DFontSizeManager::instance()->bind(title, DFontSizeManager::T4);
    QFont font = title->font();
    font.setWeight(QFont::Bold);
    title->setFont(font);
    verticalLayout->addWidget(title);
    verticalLayout->addSpacing(54);

    DLabel *icon = new DLabel;
    icon->setAlignment(Qt::AlignHCenter);
    icon->setPixmap(Utils::hidpiPixmap(":/resources/icons/file_manager.svg", QSize(96, 96)));
    icon->setAccessibleName("uosBackup_FileManagerIconLabel");
    verticalLayout->addWidget(icon, Qt::AlignHCenter);

    QHBoxLayout *hBoxLayout = new QHBoxLayout;
    hBoxLayout->setAlignment(Qt::AlignHCenter);
    m_labelDest = new DLabel;
    m_labelDest->setText(tr("Storage location:"));
    m_labelDest->setAccessibleName("uosBackup_StorageLocationLabel");
    m_labelDest->setVisible(false);
    hBoxLayout->addWidget(m_labelDest);

    m_curPartitionText = new DLabel;
    m_curPartitionText->setAccessibleName("uosBackup_PartitionTextLabel");
    m_curPartitionText->setVisible(false);
    hBoxLayout->addWidget(m_curPartitionText);

    m_destBtn = new DPushButton;
    m_destBtn->setText(tr("Select backup directory"));
    m_destBtn->setAccessibleName("uosBackup_SelectBackupDirectory");
    m_destBtn->setStyleSheet("QPushButton {"
                  "color: #0081FF;"
                  "border: none;"
                  "background-color: transparent;"
                  "}");
    hBoxLayout->addWidget(m_destBtn);
    verticalLayout->addLayout(hBoxLayout);
    verticalLayout->addSpacing(30);

    QVBoxLayout *spaceBoxLayout = new QVBoxLayout;
    spaceBoxLayout->setAlignment(Qt::AlignHCenter);

    m_storeUsed = new DProgressBar;
    m_storeUsed->setFixedSize(200, 10);
    m_storeUsed->setAlignment(Qt::AlignCenter);
    m_storeUsed->setVisible(false);
    m_storeUsed->setTextVisible(false);
    spaceBoxLayout->addWidget(m_storeUsed);
    spaceBoxLayout->addSpacing(5);

    QHBoxLayout *storeLayout = new QHBoxLayout;
    storeLayout->setAlignment(Qt::AlignHCenter);
    m_storeText = new DLabel;
    m_storeText->setAlignment(Qt::AlignCenter);
    m_storeText->setVisible(false);
    m_storeText->setAccessibleName("uosBackup_SystemBackupSize");
    storeLayout->addWidget(m_storeText);

    m_spaceManageBtn = new DPushButton;
    m_spaceManageBtn->setVisible(false);
    m_spaceManageBtn->setText(tr("Manage"));
    m_spaceManageBtn->setAccessibleName("uosBackup_Manage");
    m_spaceManageBtn->setStyleSheet("QPushButton {"
                             "color: #0081FF;"
                             "border: none;"
                             "background-color: transparent;"
                             "}");
    storeLayout->addWidget(m_spaceManageBtn);
    spaceBoxLayout->addLayout(storeLayout);
    verticalLayout->addLayout(spaceBoxLayout);
    verticalLayout->addSpacing(30);


    QVBoxLayout *remarkLayout = new QVBoxLayout;
    remarkLayout->setAlignment(Qt::AlignCenter);
    DLabel *remarks = new DLabel;
    remarks->setText(tr("Note"));
    remarks->setAccessibleName("uosBackup_SystemBackupNote");
    remarkLayout->addWidget(remarks);

    m_lineEdit = new DLineEdit;
    m_lineEdit->setFixedSize(410, 52);
    m_lineEdit->lineEdit()->setFixedSize(410,52);
    m_lineEdit->lineEdit()->setMaxLength(40);
    m_lineEdit->lineEdit()->setAlignment(Qt::AlignVCenter);
#if DTK_VERSION >= DTK_VERSION_CHECK(5, 2, 2, 13)
    m_lineEdit->setPlaceholderText(tr("Optional"));
#endif
    m_lineEdit->setAccessibleName("uosBackup_SystemBackuptextEdit");
    m_lineEdit->setFocusPolicy(Qt::ClickFocus);
    connect(m_lineEdit, &DLineEdit::textChanged, this, &SystemBackupWidget::onNoteTextChanged);
    remarkLayout->addWidget(m_lineEdit);
    verticalLayout->addLayout(remarkLayout);
    verticalLayout->addStretch(30);

    m_ostreeTips= new DLabel;
    m_ostreeTips->setAccessibleName("uosBackup_SystemBackupOStreeTips");
    m_ostreeTips->setAlignment(Qt::AlignCenter);
    m_ostreeTips->setFocusPolicy(Qt::NoFocus);
    m_ostreeTips->setStyleSheet("QLabel {"
                          "color: #FF5736;"
                          "}");
    m_tips= new DLabel;
    m_tips->setAccessibleName("uosBackup_SystemBackupTips");
    m_tips->setAlignment(Qt::AlignCenter);
    m_tips->setFocusPolicy(Qt::NoFocus);
    m_tips->setStyleSheet("QLabel {"
                          "color: #FF5736;"
                          "}");
    verticalLayout->addWidget(m_ostreeTips);
    verticalLayout->addWidget(m_tips);

    auto *startLayout = new QHBoxLayout;
    startLayout->setAlignment(Qt::AlignHCenter);

    m_cancel = new DPushButton(tr("Cancel", "button"));
    m_cancel->setAccessibleName("uosBackup_SystemBackupCancel");
    m_cancel->setFixedSize(140, 36);
    startLayout->addWidget(m_cancel);
    startLayout->addSpacing(10);
    m_start = new DSuggestButton(tr("Start Backup"));
    m_start->setAccessibleName("uosBackup_SystemBackupBackUp");
    m_start->setFixedSize(140, 36);
    if (!m_curPartitionText->isVisible()) {
        m_start->setEnabled(false);
    }
    startLayout->addWidget(m_start);

    verticalLayout->addLayout(startLayout);

    connect(m_cancel, &DPushButton::clicked, this, &SystemBackupWidget::cancel);
    connect(m_start, &DPushButton::clicked, [this] {
        Q_EMIT start(m_lineEdit->text());
    });

    connect(m_destBtn, &DPushButton::clicked, [this] {
        Q_EMIT notifySetDestPartition(this);
    });
    connect(m_spaceManageBtn, &QPushButton::clicked, this, &SystemBackupWidget::notifyBackupManage);
}

void SystemBackupWidget::onNoteTextChanged()
{
    const int maxNotesLen = 40;
    QString notes = m_lineEdit->text();
    int len = notes.length();
    if (len > maxNotesLen) {
        QLineEdit * lineEdit = m_lineEdit->lineEdit();
        int position = lineEdit->cursorPosition();
        int diff = len - maxNotesLen;
        notes.remove(position - diff, diff);
        m_lineEdit->setText(notes);
        lineEdit->setCursorPosition(position - diff);
    }
}

void SystemBackupWidget::setTips(const QString &tips)
{
    if(m_tips != nullptr) {
        m_tips->setText(tips);
    }
}

void SystemBackupWidget::setTipsStyleSheet(const QString &styleSheet)
{
    if (nullptr != m_tips) {
        m_tips->setStyleSheet(styleSheet);
    }
}

void SystemBackupWidget::setNotes(const QString &txt)
{
    m_lineEdit->setText(txt);
}

void SystemBackupWidget::setDestBtnEnabled(bool enable)
{
    m_destBtn->setEnabled(enable);
    if (enable) {
        m_destBtn->setStyleSheet("QPushButton {"
                                 "color: #0081FF;"
                                 "border: none;"
                                 "background-color: transparent;"
                                 "}");
        m_ostreeTips->setText("");
    } else {
        // 颜色设置为灰色，不能修改，OStree场景下就不支持修改系统备份的存储位置
        m_destBtn->setStyleSheet("QPushButton {"
                                 "color: rgba(193, 194, 195);"
                                 "border: none;"
                                 "background-color: transparent;"
                                 "}");
        m_ostreeTips->setText(tr("The system uses atomic updates and you cannot change the backup location for system backup."));
    }
}

void SystemBackupWidget::onThemeChange()
{

}

void SystemBackupWidget::setDestPartitionText(const QJsonObject &jsonObject)
{
    Partition partition;
    partition.unmarshal(jsonObject);
    if (partition.name.isEmpty() && jsonObject.contains("disk")) {
        partition.name = jsonObject.value("disk").toString().trimmed();
    }

    if ((0 == partition.size) && jsonObject.contains("size")) {
        partition.size = Utils::parsePartitionSize(jsonObject.value("size").toString());
    }

    if ((0 == partition.used) && jsonObject.contains("used")) {
        partition.used = Utils::parsePartitionSize(jsonObject.value("used").toString());
    }

    if ((0 == partition.free) && jsonObject.contains("free")) {
        partition.free = Utils::parsePartitionSize(jsonObject.value("free").toString());
    }

    if (Utils::isImmutableSystem()) {
        m_curPartitionText->setText("/persistent/ostree/snapshot");
    } else {
        m_curPartitionText->setText(partition.name);
    }
    m_destBtn->setText(tr("Change"));
    m_destBtn->setAccessibleName("uosBackup_SystemBackupChange");
    if (0 == partition.size) {
        return;
    }

    m_storeUsed->setValue((int)(partition.used * 100 / partition.size));
    m_storeUsed->setVisible(true);
    m_storeText->setText(tr("Size: %1/%2")
        .arg(Utils::byte2DisplaySize(partition.used))
        .arg(Utils::byte2DisplaySize(partition.size)));
    m_storeText->setVisible(true);
    m_spaceManageBtn->setVisible(true);
    m_labelDest->setVisible(true);
    m_curPartitionText->setVisible(true);
    m_start->setEnabled(true);
}
