//
// Created by uos on 2022/4/19.
//

#include "UserDataBackupWidget.h"
#include "utils/Utils.h"
#include <DLabel>
#include <DFontSizeManager>
#include <QHeaderView>
#include <DDialog>


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

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

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

    DLabel *title = new DLabel;
    title->setText(tr("Data Backup"));
    title->setAccessibleName("uos_UserDataBackup_DataBackupTitle");
    title->setAlignment(Qt::AlignCenter);
    DFontSizeManager::instance()->bind(title, DFontSizeManager::T4);
    QFont font = title->font();
    font.setWeight(QFont::Bold);
    verticalLayout->addWidget(title);


    DLabel *subTitle = new DLabel;
    subTitle->setText(tr("Select the data to back up and customize a backup location."));
    subTitle->setAccessibleName("uos_UserDataBackup_DataBackupSubTitle");
    subTitle->setAlignment(Qt::AlignCenter);
    verticalLayout->addWidget(subTitle);

    DLabel *selectedBackup = new DLabel;
 //   selectedBackup->setText(tr("Backup files have been selected"));
    subTitle->setAccessibleName("uos_UserDataBackup_SelectedBackupLabel");
    selectedBackup->setAlignment(Qt::AlignLeft);
    verticalLayout->addWidget(selectedBackup);

    m_model = new QStandardItemModel;
    m_treeView = new SelectFileTreeView;
    m_treeView->setAccessibleName("uos_UserDataBackup_TreeView");
    m_treeView->setModel(m_model);
    m_treeView->setItemsExpandable(true);
    m_treeView->header()->setSortIndicatorShown(false);
    //m_treeView->header()->setSectionResizeMode(QHeaderView::ResizeToContents);
    m_treeView->setAlwaysChecked(true);
    verticalLayout->addWidget(m_treeView);
    verticalLayout->addSpacing(20);


    QHBoxLayout *hBoxlayout1 = new QHBoxLayout;
    DLabel *lbStoreDir = new DLabel;
    lbStoreDir->setText(tr("Backup directory"));
    lbStoreDir->setAccessibleName("uos_UserDataBackup_BackupDirectory");
    lbStoreDir->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    hBoxlayout1->addWidget(lbStoreDir);
    hBoxlayout1->addSpacing(8);
    m_comboBox = new DComboBox;
    m_comboBox->setFixedWidth(734);
    m_comboBox->setAccessibleName("uos_UserDataBackup_ComboBox");
    hBoxlayout1->addWidget(m_comboBox);
    verticalLayout->addLayout(hBoxlayout1);
    verticalLayout->addSpacing(10);

    QHBoxLayout *hBoxLayout2 = new QHBoxLayout;
    DLabel *lbRemark = new DLabel;
    lbRemark->setText(tr("Note"));
    lbRemark->setAccessibleName("uos_UserDataBackup_Note");
    lbRemark->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    hBoxLayout2->addWidget(lbRemark);
    hBoxLayout2->addSpacing(8);
    m_remark = new DLineEdit;
    m_remark->setFixedWidth(m_comboBox->width());
#if DTK_VERSION >= DTK_VERSION_CHECK(5, 2, 2, 13)
    m_remark->setPlaceholderText(tr("Optional"));
#endif
    m_remark->setAccessibleName("uos_UserDataBackup_NoteContents");
    m_remark->setFocusPolicy(Qt::ClickFocus);
    connect(m_remark, &DLineEdit::textChanged, this, &UserDataBackupWidget::onNoteTextChanged);
    hBoxLayout2->addWidget(m_remark);
    verticalLayout->addLayout(hBoxLayout2);
    verticalLayout->addSpacing(10);

    QHBoxLayout *hBoxLayout3 = new QHBoxLayout;
    hBoxLayout3->setAlignment(Qt::AlignHCenter);
    m_cancelBtn = new DPushButton;
    m_cancelBtn->setText(tr("Cancel", "button"));
    m_cancelBtn->setAccessibleName("uos_UserDataBackup_Cancel");
    m_cancelBtn->setFixedSize(140, 36);
    m_cancelBtn->setStyleSheet("QPushButton {"
                               "color: #000000;"
                               "border:2px solid;"
                               "border-color: rgb(235,236,237);"
                               "border-radius:10px;"
                               "padding:2px 4px;"
                               "background-color: transparent;"
                               "}"
                               "QPushButton:hover{"
                               "color: #000000;"
                               "border:2px solid;"
                               "border-color: rgb(235,236,237);"
                               "border-radius:10px;"
                               "padding:2px 4px;"
                               "background-color:rgba(0,0,0,0.03);"
                               "}");

    m_startBtn = new DSuggestButton;
    m_startBtn->setText(tr("Start Backup"));
    m_startBtn->setAccessibleName("uos_UserDataBackup_BackUp");
    m_startBtn->setFixedSize(140, 36);
    hBoxLayout3->addWidget(m_cancelBtn);
    hBoxLayout3->addWidget(m_startBtn);
    verticalLayout->addLayout(hBoxLayout3);

    connect(m_cancelBtn, &QPushButton::clicked, this, &UserDataBackupWidget::cancel);
    connect(m_startBtn, &DPushButton::clicked, [this] {
        Q_EMIT start(m_remark->text());
    });
}

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

void UserDataBackupWidget::setComboBoxText(const QString &text)
{
    m_comboBox->clear();
    m_comboBox->addItem(text);
    m_comboBox->setEnabled(false);
}

void UserDataBackupWidget::setRemark(const QString &remark)
{
    m_remark->setText(remark);
}

QString UserDataBackupWidget::getDestDeviceUUID()
{
    if (m_partitionList.isEmpty()) {
        DDialog dialog(this);
        dialog.setMessage(tr("Please insert a removable disk, supported format: ext4, btrfs, xfs"));
        dialog.setIcon(QIcon::fromTheme("dialog-warning"));
        QRect rect = geometry();
        dialog.move(rect.center());
        dialog.moveToCenter();
        dialog.exec();
        return "";
    } else if (m_comboBox->count() == m_partitionList.size()) {
        Partition selectPartition = m_partitionList.at(m_comboBox->currentIndex());
        if (!selectPartition.fsTypeSupported) {
            DDialog dlg(this);
            dlg.setMessage(::QObject::tr("The file system of the device is unsupported. Please select one in ext4, btrfs, xfs format."));
            dlg.setIcon(QIcon::fromTheme("dialog-warning"));
            QRect rect = geometry();
            dlg.move(rect.center());
            dlg.moveToCenter();
            dlg.exec();
            return "";
        }
        return selectPartition.uuid;
    }
    return "";
}

void UserDataBackupWidget::setFiles(const QList<FileItem> &fileItemList)
{
    m_model->clear();
    m_model->setHorizontalHeaderLabels({tr("Name"), tr("Type")});
    auto root = m_model->invisibleRootItem();
    for (auto &file : fileItemList) {
        auto nameItem = new QStandardItem(file.fileName);
        nameItem->setCheckable(true);
        nameItem->setCheckState(Qt::Checked);
        QString fileType = file.fileType == FileType::Dir ? tr("Directory") : tr("File");
        auto typeItem = new QStandardItem(fileType);
        if (file.fileType == FileType::Dir) {
            nameItem->setIcon(QIcon::fromTheme(":/resources/icons/folder.svg"));
        } else {
            nameItem->setIcon(QIcon::fromTheme(":/resources/icons/file.svg"));
        }
        root->appendRow({nameItem, typeItem});
        if (!children().isEmpty()) {
            for (auto &child : file.children) {
                auto childNameItem = new QStandardItem(child.fileName);
                childNameItem->setCheckable(true);
                childNameItem->setCheckState(Qt::Checked);
                QString childFileType = child.fileType == FileType::Dir ? tr("Directory") : tr("File");
                auto childTypeItem = new QStandardItem(childFileType);
                if (child.fileType == FileType::Dir) {
                    childNameItem->setIcon(QIcon::fromTheme(":/resources/icons/folder.svg"));
                } else {
                    childNameItem->setIcon(QIcon::fromTheme(":/resources/icons/file.svg"));
                }
                nameItem->appendRow({childNameItem, childTypeItem});
            }
        }
    }

    m_treeView->setColumnWidth(0, 650);
    QHeaderView * headerView = m_treeView->header();
    headerView->setSectionResizeMode(0, QHeaderView::ResizeMode::Fixed);
    headerView->setSectionResizeMode(1, QHeaderView::ResizeMode::Fixed);
}

void UserDataBackupWidget::onThemeChange()
{
    if (DGuiApplicationHelper::instance()->themeType() == DGuiApplicationHelper::ColorType::LightType) {
        m_treeView->setStyleSheet("QTreeView::indicator:enabled:checked {"
                                  "image: url(:/resources/icons/Checked-Normal-Light.svg)"
                                  "}"
                                  "QTreeView::indicator:enabled:unchecked {"
                                  "image: url(:/resources/icons/UnChecked-Normal-Light.svg)"
                                  "}"
                                  "QTreeView::indicator:enabled:indeterminate {"
                                  "image: url(:/resources/icons/Mixed-Normal-Light.svg)"
                                  "}");
    }

}

