//
// Created by dtx on 2022/5/31.
//

#include "AdvancedGhostWidget.h"
#include "utils/Utils.h"
#include "utils/Device.h"
#include <QWidget>
#include <QLabel>
#include <QPushButton>
#include <QVBoxLayout>
#include <QFileDialog>
#include <QDir>
#include <DFontSizeManager>

AdvancedGhostWidget::AdvancedGhostWidget(QWidget *parent) : QWidget(parent)
{
    this->setAccessibleName("uosAdvanced_AdvancedGhostWidget");
    // 主题变换
    m_guiHelper = Dtk::Gui::DGuiApplicationHelper::instance();
    connect(m_guiHelper, &Dtk::Gui::DGuiApplicationHelper::themeTypeChanged, this, &AdvancedGhostWidget::onThemeChange);
    // 初始化UI
    initUI();
    initConnect();
}

void AdvancedGhostWidget::setDestDirText(const QString &path)
{
    QString pathText = tr("Storage location:") + " " + path;
    QFontMetrics fontWidth(m_destPathLabel->font());
    QString elideNote = fontWidth.elidedText(pathText, Qt::ElideMiddle, m_destPathLabel->width(), Qt::AlignLeft | Qt::AlignBottom | Qt::TextSingleLine);
    m_destPathLabel->setText(elideNote);
    (elideNote.indexOf("…") != -1) ? m_destPathLabel->setToolTip(path) : m_destPathLabel->setToolTip("");

    m_selectPath->setText(path.isEmpty() ? tr("Select a directory") : tr("Reselect a directory"));
    m_destPathLabel->setVisible(!path.isEmpty());

    // m_destPathLabel->setFixedHeight(m_destPathLabel->heightForWidth(m_destPathLabel->width()));
}

QString AdvancedGhostWidget::getDestDirText()
{
    QString labelText = m_destPathLabel->text();
    if (labelText.isEmpty()){
        return QString();
    }

    if (labelText.indexOf("…") != -1) {
        labelText = m_destPathLabel->toolTip();
    } else {
        labelText.replace(tr("Storage location:") + " ","");
    }

    return labelText;
}

void AdvancedGhostWidget::setResultInfo(const QString &info, bool error)
{
    setErrorInfo(info, error);
    startCalculateTip(false);

    m_startMake->setEnabled(!getDestDirText().isEmpty());
}

void AdvancedGhostWidget::setErrorInfo(const QString &info, bool normalStyle)
{
    m_errorInfoLabel->setText(info);
    if (normalStyle) {
        QLabel styleLabel;
        m_errorInfoLabel->setStyleSheet(styleLabel.styleSheet());
    } else {
        m_errorInfoLabel->setStyleSheet("QLabel {"
                                        "color: #FF0000;"
                                        "border: none;"
                                        "background-color: transparent;"
                                        "}");
    }

    if (info.isEmpty()) {
        m_errorInfoLabel->hide();
    } else {
        m_errorInfoLabel->show();
    }
}

void AdvancedGhostWidget::initUI()
{
    m_mainLayout = new QVBoxLayout;
    m_mainLayout->setContentsMargins(0, 10, 0, 10);

    // 初始化主标题和副标题
    m_title = new QLabel;
    m_title->setText(tr("System Clone"));
    m_title->setAccessibleName("uosAdvancedSystemCloneTitle");
    m_title->setAlignment(Qt::AlignHCenter);
    DFontSizeManager::instance()->bind(m_title, DFontSizeManager::T3);
    QFont font = m_title->font();
    font.setWeight(QFont::DemiBold);
    m_title->setFont(font);
    QPalette titlePalette;
    titlePalette.setColor(QPalette::BrightText, QColor(qRgb(0,26,46)));
    m_title->setPalette(titlePalette);

    m_subTitle = new DTipLabel;
    m_subTitle->setText(tr("Select a directory to save the .uimg image file"));
    m_subTitle->setAccessibleName("uosAdvancedGhost_GhostSubTitle");
    QPalette subtitlePalette;
    subtitlePalette.setColor(QPalette::BrightText, QColor(qRgba(0,0,0,0.6)));
    m_subTitle->setPalette(subtitlePalette);
    QFont subTitleFont = m_subTitle->font();
    subTitleFont.setWeight(QFont::Light);
    m_subTitle->setFont(subTitleFont);
    DFontSizeManager::instance()->bind(m_subTitle, DFontSizeManager::T8);

    // 添加选择镜像保存目录组件
    QLabel *imgPic = new QLabel;
    imgPic->setAccessibleName("uosAdvancedGhost_FileManegerLabel");
    imgPic->setPixmap(Utils::hidpiPixmap(":/resources/icons/machine-backup.svg", QSize(144, 144)));
    m_destPathLabel = new QLabel;
    m_destPathLabel->setAccessibleName("uosAdvancedGhost_StorageLocation");
    m_destPathLabel->setFixedWidth(310);
    m_destPathLabel->setAlignment(Qt::AlignCenter);
    m_destPathLabel->hide();
    m_selectPath = new DPushButton;
    m_selectPath->setText(tr("Select a directory"));
    m_selectPath->setAccessibleName("uosAdvancedGhost_SelectADirectory");
    m_selectPath->setStyleSheet("QPushButton {"
                                "color: #0081FF;"
                                "border: none;"
                                "background-color: transparent;"
                                "}");

    m_calculateTip = new DSpinner;
    m_calculateTip->setAccessibleName("uosAdvancedGhost_DSpinner");
    m_calculateTip->hide();
    m_calculateTip->setFixedSize(16, 16);
    m_calculateTip->setFocusPolicy(Qt::NoFocus);
    m_errorInfoLabel = new QLabel();
    m_errorInfoLabel->hide();
    m_errorInfoLabel->setAccessibleName("uosAdvancedGhost_ErrorInfoLabel");

    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->setAccessibleName("uosAdvancedGhost_calculateTipWidget");
    calculateTipWidget->setFixedHeight(36);
    calculateTipWidget->setLayout(calculateTipLayout);

    // 初始化按钮控件
    m_cancel = new DPushButton;
    m_cancel->setFixedSize(140,36);
    m_cancel->setText(tr("Cancel", "button"));
    m_cancel->setAccessibleName("uosAdvancedGhost_Cancel");
    m_startMake = new DSuggestButton;
    m_startMake->setFixedSize(140, 36);
    m_startMake->setText(tr("Create"));
    m_startMake->setAccessibleName("uosAdvancedGhost_Create");
    m_startMake->setEnabled(false);
    QHBoxLayout *buttonsLayout = new QHBoxLayout;
    buttonsLayout->setSpacing(10);
    buttonsLayout->addStretch();
    buttonsLayout->addWidget(m_cancel);
    buttonsLayout->addWidget(m_startMake);
    buttonsLayout->addStretch();

    m_mainLayout->addWidget(m_title, 0, Qt::AlignHCenter);
    m_mainLayout->addWidget(m_subTitle, 0, Qt::AlignHCenter);
    m_mainLayout->addSpacing(90);
    m_mainLayout->addWidget(imgPic, 0, Qt::AlignHCenter);
    m_mainLayout->addSpacing(3);
    m_mainLayout->addWidget(m_destPathLabel, 0, Qt::AlignHCenter);
    m_mainLayout->addSpacing(10);
    m_mainLayout->addWidget(m_selectPath, 0, Qt::AlignHCenter);
    m_mainLayout->addStretch();
    m_mainLayout->addStretch();
    m_mainLayout->addStretch();
    m_mainLayout->addWidget(calculateTipWidget, 0, Qt::AlignHCenter);
    m_mainLayout->addLayout(buttonsLayout);
    setLayout(m_mainLayout);
}

void AdvancedGhostWidget::initConnect()
{
    connect(m_selectPath,&DPushButton::clicked, this, &AdvancedGhostWidget::selectPathBtnClicked, Qt::QueuedConnection);
    connect(m_cancel,    &DPushButton::clicked, this, &AdvancedGhostWidget::cancelBtnSignal);
    connect(m_startMake, &DSuggestButton::clicked, this, &AdvancedGhostWidget::startMakeBtnClicked, Qt::QueuedConnection);
}

void AdvancedGhostWidget::startCalculateTip(bool start)
{
    if (start) {
        m_calculateTip->start();
        m_calculateTip->show();
        m_startMake->setEnabled(false);
        m_selectPath->setEnabled(false);
    } else {
        m_calculateTip->hide();
        m_calculateTip->stop();
        m_startMake->setEnabled(true);
        m_selectPath->setEnabled(true);
    }
}

void AdvancedGhostWidget::startMakeBtnClicked()
{
    QString labelText = getDestDirText();
    Q_EMIT startMakeBtnSignal(labelText);
}

void AdvancedGhostWidget::selectPathBtnClicked()
{
    // 显示选择目录弹框
    QString srcDirStr = QFileDialog::getExistingDirectory(this->parentWidget(),"", "", QFileDialog::ReadOnly);
    if (srcDirStr.isEmpty()) {
        setResultInfo("", false);
        return;
    }

    QString fstype;
    QString devPath;
    Utils::getFsTypeAndDevicePathByDir(srcDirStr, fstype, devPath);
    if (!Device::isFsTypeSupportedGhost(fstype)) {
        setDestDirText("");
        setResultInfo(tr("The file system of the selected directory is unsupported. Please select one on a disk in ext4, btrfs, xfs format."), false);
        return;
    }

#if 0
    if (srcDirStr.startsWith("/media/")) {
        if (Utils::isDeviceRemoveble(devPath)) {
            setDestDirText("");
            setResultInfo(tr("Select a local directory please. Saving the file to an external device is not supported."), false);
            return;
        }
    }
#endif

    setErrorInfo(tr("Calculating space..."), true);
    startCalculateTip(true);
    Q_EMIT checkSpaceSignal(srcDirStr);
}

void AdvancedGhostWidget::onThemeChange()
{

}

void AdvancedGhostWidget::setWidgetEnable(bool enable)
{
    if (nullptr != m_startMake) {
        m_startMake->setEnabled(enable);
    }

    if (nullptr != m_selectPath) {
        m_selectPath->setEnabled(enable);
    }
}
