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

#include "AdvancedWidget.h"
#include "common/ItemFrame.h"
#include "common/HelpDialog.h"
#include "utils/Utils.h"
#include "utils/Device.h"
#include <QVBoxLayout>
#include <QSpacerItem>
#include <DFontSizeManager>
#include <QStackedLayout>
#include <QLabel>
#include <DDialog>
#include <QDebug>
#include <QScreen>

static const int ITEM_FRAME_HEIGHT_VERTICAL_LAYOUT = 85;
static const int ITEM_FRAME_WIDTH_VERTICAL_LAYOUT = 600;

AdvancedWidget::AdvancedWidget(DWidget *parent) : DWidget(parent)
{
    this->setAccessibleName("AdvancedWidget");
    m_bDirectionRTL = Utils::isDirectionRTL();

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

void AdvancedWidget::initHelpLayout()
{
    m_helpDialog = new HelpDialog();
    m_helpDialog->setFixedSize(QSize(380,90));
    QList<HelpInfoItem> helpInfos;
    HelpInfoItem infoItem;
    infoItem.title = ::QObject::tr("System Clone");
    infoItem.subTitle = ::QObject::tr("One click clone the system and data, and can be installed to other device.");
    helpInfos.append(infoItem);
    m_helpDialog->setContentText(helpInfos);
}

void AdvancedWidget::initUI()
{
    int uiLayout = this->getAdvanceUiLayoutType();
    QVBoxLayout *mainLayout = new QVBoxLayout;
    if (UI::UI_LAYOUT_ADVANCE_HORIZONTAL == uiLayout) {
        mainLayout->setContentsMargins(0, 20, 0, 10);
    } else if (UI::UI_LAYOUT_ADVANCE_VERTICAL == uiLayout) {
        mainLayout->setContentsMargins(0, 57, 0, 5);
    }

    // 初始化主标题和副标题
    m_title = new QLabel;
    m_title->setText(tr("Choose an advanced function"));
    m_title->setAccessibleName("uosAdvanced_ChooseTitle");
    m_title->setAlignment(Qt::AlignHCenter);
    DFontSizeManager::instance()->bind(m_title, DFontSizeManager::T6);
    QFont font = m_title->font();
    font.setWeight(QFont::Medium);
    m_title->setFont(font);
    QPalette titlePalette;
    titlePalette.setColor(QPalette::BrightText, QColor(qRgba(0,0,0,0.7)));
    m_title->setPalette(titlePalette);
    m_subTitle = new QLabel;
    m_subTitle->setText("");
    m_subTitle->setAccessibleName("uosAdvanced_ChooseSubTitle");
    m_subTitle->hide();

    m_nextBtn = new DPushButton;
    m_nextBtn->setText(tr("Next"));
    m_nextBtn->setAccessibleName("uosAdvanced_Next");
    m_nextBtn->setFixedSize(200, 36);
    m_nextBtn->setEnabled(false);

    // 主界面上的组合控件
    m_itemGhostFrame = new ItemFrame(
            ::QObject::tr("System Clone"),
            ::QObject::tr("One click clone the system and data, and can be installed to other device."),
            ":/resources/icons/make_ghost.svg", this);
    m_itemGhostFrame->setLayoutStype(uiLayout);
    m_itemGhostFrame->setItemFrameAccessibleName("uos_itemGhostFrame");
    m_itemGhostFrame->setTitleAccessibleName("uos_SystemClone");
    m_itemGhostFrame->setDescriptionAccessibleName("uos_SystemCloneDescription");
    m_itemGhostFrame->setIconAccessibleName("uos_SystemCloneIcon");
    m_itemGhostFrame->setCheckIconAccessibleName("uos_SystemCloneCheckIcon");

    QHBoxLayout *nextBtnLayout = new QHBoxLayout;
    if (UI::UI_LAYOUT_ADVANCE_HORIZONTAL == uiLayout) {
        // 下一步按钮的布局
        QLabel *leftLabel = new QLabel;
        leftLabel->setFixedSize(20, 20);
        m_helpLabel = new QLabel;
        m_helpLabel->setAccessibleName("uosAdvanced_HelpLabel");
        m_helpLabel->installEventFilter(this);
        Dtk::Gui::DGuiApplicationHelper::ColorType themeType =  Dtk::Gui::DGuiApplicationHelper::instance()->themeType();
        m_helpLabel->setPixmap(HelpDialog::getPixMapByThemeType(themeType));
        m_helpLabel->setFixedSize(20, 20);

        nextBtnLayout->setContentsMargins(13, 0, 13, 0);
        nextBtnLayout->addWidget(leftLabel, 0, Qt::AlignLeft);
        nextBtnLayout->addWidget(m_nextBtn, 0, Qt::AlignHCenter);
        nextBtnLayout->addWidget(m_helpLabel, 0, Qt::AlignRight);
        this->initHelpLayout();

        m_itemGhostFrame->setFixedSize(QSize(300,260));
        m_itemGhostFrame->setIconPixmap(":/resources/icons/make_ghost.svg", QSize(136, 136));
    } else if (UI::UI_LAYOUT_ADVANCE_VERTICAL == uiLayout) {
        nextBtnLayout->setContentsMargins(0, 0, 0, 0);
        nextBtnLayout->addWidget(m_nextBtn, 0, Qt::AlignHCenter);

        m_itemGhostFrame->setFixedSize(QSize(ITEM_FRAME_WIDTH_VERTICAL_LAYOUT,ITEM_FRAME_HEIGHT_VERTICAL_LAYOUT));
        m_itemGhostFrame->setIconPixmap(":/resources/icons/make_ghost.svg", QSize(56, 56));
    }
    m_itemGhostFrame->initLayout();
    m_itemGhostFrame->showDescription(true);

    m_nextButtonWidget = new QWidget;
    m_nextButtonWidget->setAccessibleName("uosAdvanced_NextButtonWidget");
    m_nextButtonWidget->setLayout(nextBtnLayout);

    mainLayout->addWidget(m_title, 0, Qt::AlignHCenter);
    mainLayout->addWidget(m_subTitle, 0, Qt::AlignCenter);
    if (UI::UI_LAYOUT_ADVANCE_HORIZONTAL == uiLayout) {
        mainLayout->addStretch();
    } else if (UI::UI_LAYOUT_ADVANCE_VERTICAL == uiLayout) {
        mainLayout->setSpacing(35);
    }

    mainLayout->addWidget(m_itemGhostFrame, 0, Qt::AlignHCenter);
    mainLayout->addStretch();
    mainLayout->addStretch();
    mainLayout->addWidget(m_nextButtonWidget);

    this->setLayout(mainLayout);
}

int AdvancedWidget::getAdvanceUiLayoutType()
{
    int defaultLayout = Utils::getUILayoutType(UI::UI_ADVANCE_MODULE);
    if (-1 == defaultLayout) {
        qCritical()<<"getAdvanceUiLayoutType failed";
    }
    return defaultLayout;
}

void AdvancedWidget::initConnect()
{
    connect(m_nextBtn, &DPushButton::clicked, this, &AdvancedWidget::onNextBtnBtnClicked);
    connect(m_itemGhostFrame, &ItemFrame::clicked, this, &AdvancedWidget::onItemIcoBtnClicked);

    connect(this, &AdvancedWidget::enter, this, [=] {
        QPoint point = m_helpLabel->mapToGlobal(QPoint());
        QPoint nextBtnPoint = m_nextBtn->mapToGlobal(QPoint());
        int x = point.x();
        int w = m_helpDialog->width();
        if (x > nextBtnPoint.x()) {
            x -= w;
        }
        m_helpDialog->move(x, point.y() - m_helpDialog->height() -10);
        m_helpDialog->raise();
        m_helpDialog->activateWindow();
        m_helpDialog->show();
    });

    connect(this, &AdvancedWidget::leave, this, [=] {
        m_helpDialog->hide();
        if (!this->isActiveWindow()) {
            this->raise();
            this->activateWindow();
        }
    });
}

void AdvancedWidget::onItemIcoBtnClicked()
{
    m_nextBtn->setEnabled(true);
}

void AdvancedWidget::showNotSupportDlg(const QString &msg)
{
    DDialog dlg(this);
    dlg.setMessage(msg);
    dlg.setIcon(QIcon::fromTheme("dialog-warning"));
    QRect rect = geometry();
    dlg.move(rect.center());
    dlg.moveToCenter();

    dlg.exec();
    return;
}

void AdvancedWidget::setLVM(bool isLVM)
{
    m_isLVMOnly = isLVM;
}

void AdvancedWidget::setEncrypted(bool isEncrypted)
{
    m_isEncrypted = isEncrypted;
}

void AdvancedWidget::checkAdminAuthority(AuthorityType type)
{
    if (nullptr == m_adminAuthUtils) {
        m_adminAuthUtils = new AuthorityUtils();
        connect(m_adminAuthUtils, &AuthorityUtils::notifyAdminAuthority, this, &AdvancedWidget::doAdminAuthorityTask);
    }

    m_adminAuthUtils->authorization(type);
}

void AdvancedWidget::doAdminAuthorityTask(bool result, int type)
{
    if (result) {
        AuthorityType authType = static_cast<AuthorityType>(type);
        // 更新目标存储位置
        if (AuthorityType::GhostBackup == authType) {
            Q_EMIT showGhostWidgetSignal();
        }
    }
}

void AdvancedWidget::onNextBtnBtnClicked()
{
    static QString osEditionType = Utils::getOSEditionType();
    QString encryptMsg = tr("Your system contains encrypted partition, system clone is not supported.");
    QString lvmMsg = tr("System clone is not supported in the current environment.");
    QString notFullInstallMsg = tr("System clone is not supported in the current environment.");

    QString fstabFile = "/etc/fstab";
    QStringList sysMountPointList;
    bool isFullInstall = Device::isFullDiskInstall(fstabFile, sysMountPointList);
    if (!isFullInstall) {
        QString msg = tr("System clone is not supported in the current environment.");
        this->showNotSupportDlg(msg);
        return;
    }

    if ("Community" == osEditionType) {
        this->showNotSupportDlg(lvmMsg);
        return;
    }

    if (m_isEncrypted) {
        this->showNotSupportDlg(encryptMsg);
        return;
    }

    if (m_isLVMOnly) {
        this->showNotSupportDlg(lvmMsg);
        return;
    }

    this->checkAdminAuthority(AuthorityType::GhostBackup);
}

void AdvancedWidget::onThemeChange(Dtk::Gui::DGuiApplicationHelper::ColorType themeType)
{
    if (nullptr != m_helpLabel) {
        m_helpLabel->setPixmap(HelpDialog::getPixMapByThemeType(themeType));
    }
}

bool AdvancedWidget::eventFilter(QObject* watched, QEvent* event)
{
    if (watched == m_helpLabel) {
        switch (event->type()) {
            case QEvent::Enter: Q_EMIT enter(); break;
            case QEvent::Leave: Q_EMIT leave(); break;
            default: break;
        }
    }

    return QWidget::eventFilter(watched, event);
}
