/*
 * Copyright (C) 2020, KylinSoft Co., Ltd.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
#include "aiservicedialog.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QPixmap>
#include <QApplication>
#include <QGuiApplication>
#include <QScreen>
#include <QCursor>
#include <QMetaObject>
#include <QProcess>
#include <QStyle>
#include <QStyleOptionButton>
#include <ukui-log4qt.h>
#include <qgsettings.h>

#include "windowhelper.h"

AiServiceDialog::AiServiceDialog(QWidget *parent) : QDialog(parent)
{
#ifdef UKUI_WINDOWHELPER_SUPPORT
    UkuiWindowHelper *ukuiWindowHelper = new UkuiWindowHelper(this);
    ukuiWindowHelper->removeTitleBar();
    ukuiWindowHelper->setSkipTaskBar(true);
    ukuiWindowHelper->setSkipSwitcher(true);
#else
    kdk::UkuiStyleHelper::self()->removeHeader(this);
    kdk::WindowManager::setSkipTaskBar(this->windowHandle(), true);
    kdk::WindowManager::setSkipSwitcher(this->windowHandle(),true);
#endif

    initLayout();
    initConnect();
}

AiServiceDialog::~AiServiceDialog()
{

}

void AiServiceDialog::setLowVersionText()
{
    titleLabel->setText(tr("Current AI subsystem version is low"));
    detailLabel->setText(tr("The AI subsystem version is too low, and the AI assistant features are limited. Please update the system in System Settings > Updates to unlock the full AI assistant functionality."));
    cancelButton->hide();
    updateFixedSize();
    refreshButtonElide();
    return;
}

void AiServiceDialog::initLayout()
{
    this->setWindowTitle(QString(" "));
    this->setFixedWidth(452);
    this->setStyleSheet("QDialog { background-color: white; }");

    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(0, 0, 0, 24);
    mainLayout->setSpacing(0);

    QHBoxLayout *tipsLayout = new QHBoxLayout(this);
    QHBoxLayout *contentLayout = new QHBoxLayout(this);
    contentLayout->setContentsMargins(20, 0, 0, 0);


    closeButton = new QPushButton;
    closeButton->setAccessibleName("kylin-aiassistant_QPushButton_closeButton");
    closeButton->setFlat(true);
    closeButton->setFixedSize(32, 32);
    closeButton->setProperty("isWindowButton",  0x2);
    closeButton->setProperty("useIconHighlightEffect", 0x8);
    closeButton->setIcon(QIcon::fromTheme("window-close-symbolic"));
    closeButton->setToolTip(tr("Close"));

    QWidget *titleWidget = new QWidget();
    titleWidget->setAccessibleName("kylin-aiassistant_QWidget_titleWidget");
    titleWidget->setFixedSize(452, 40);
    QHBoxLayout *titleHLayout = new QHBoxLayout(titleWidget);
    titleHLayout->setContentsMargins(8, 0, 4, 0);
    titleHLayout->addStretch();
    titleHLayout->addWidget(closeButton);
    mainLayout->addWidget(titleWidget);

    iconLabel = new QLabel(this);
    iconLabel->setPixmap(QPixmap(":/icon/icon/hint.svg").scaled(16, 16));
    iconLabel->setContentsMargins(28, 2, 0, 144);
    titleLabel = new QLabel(tr("AI service unavailable"));
    titleLabel->setFixedWidth(380);
    titleLabel->setWordWrap(true);
    QFont titleFont = titleLabel->font();
    titleFont.setBold(true);
    titleLabel->setFont(titleFont);

    tipsLayout->setContentsMargins(24, 8, 24, 0);
    tipsLayout->addWidget(iconLabel);
    tipsLayout->addWidget(titleLabel);

    mainLayout->addLayout(tipsLayout);

    detailLabel = new QLabel(tr("The AI subsystem is not detected. The AI service of the application cannot be used. Please go to System Settings > AI Module Management page to install it."));
    detailLabel->setWordWrap(true);
    detailLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
    contentLayout->setContentsMargins(48, 8, 24, 0);
    contentLayout->addWidget(detailLabel);
    mainLayout->addLayout(contentLayout);

    QHBoxLayout *buttonLayout = new QHBoxLayout(this);
    cancelButton = new QPushButton(tr("Cancel"));
    cancelButton->setAccessibleName("kylin-aiassistant_QQPushButton_cancelButton");
    cancelButton->setFixedSize(88, 36);

    goButton = new QPushButton(tr("go now"));
    goButton->setAccessibleName("kylin-aiassistant_QPushButton_okButton");
    goButton->setFixedSize(88, 36);

    goButton->setProperty("isImportant", true);
    goButton->setDefault(true);

    buttonLayout->setContentsMargins(24, 0, 24, 0);
    buttonLayout->addStretch();
    buttonLayout->addWidget(cancelButton);
    buttonLayout->addWidget(goButton);
    mainLayout->addStretch();
    mainLayout->addLayout(buttonLayout);

    m_cancelButtonFullText = cancelButton->text();
    m_goButtonFullText = goButton->text();
}

void AiServiceDialog::initConnect()
{
    connect(cancelButton, &QPushButton::clicked, this, &AiServiceDialog::reject);
    connect(goButton, &QPushButton::clicked, this, &AiServiceDialog::openUkuiControlCenter);
    connect(closeButton, &QPushButton::clicked, this, &AiServiceDialog::reject);

    QGSettings *themeData = new QGSettings("org.ukui.style");
    const qreal fontSize = themeData->get("systemFontSize").toFloat();
    const QString fontFamily = themeData->get("systemFont").toString();
    applyFont(fontSize, fontFamily);

    connect(themeData, &QGSettings::changed, this, [=](const QString &key) {
        const qreal fontSizeKey = themeData->get(QStringLiteral("systemFontSize")).toString().toFloat();
        const QString fontFamilyKey = themeData->get("systemFont").toString();
        applyFont(fontSizeKey, fontFamilyKey);
    });
}

void AiServiceDialog::openUkuiControlCenter()
{
    QProcess process;
    QString command = "ukui-control-center";
    QStringList arguments;
    arguments << "-m" << "upgrade";
    process.startDetached(command, arguments);
    process.waitForFinished(-1);
    // 检查进程是否正常退出
    if (process.exitStatus() == QProcess::NormalExit) {
        KyInfo() << "ukui-control-center successfully!";
    } else {
        KyInfo() << "Failed  to open ukui-control-center";
    }
    this->close();
}

void AiServiceDialog::showEvent(QShowEvent *event)
{
    QDialog::showEvent(event);
    QGSettings *themeData = new QGSettings("org.ukui.style");
    const qreal fontSize = themeData->get("systemFontSize").toFloat();
    const QString fontFamily = themeData->get("systemFont").toString();
    KyInfo() << "setLowVersionText-----initialSize----" << fontSize << fontFamily;
    applyFont(fontSize, fontFamily);
}

void AiServiceDialog::elidePushButtonText(QPushButton *btn, const QString &fullText)
{
    if (!btn)
        return;

    if (fullText.isEmpty()) {
        btn->setText(QString());
        btn->setToolTip(QString());
        return;
    }

    if (!btn->isVisible()) {
        btn->setText(fullText);
        btn->setToolTip(QString());
        return;
    }

    QStyleOptionButton opt;
    opt.initFrom(btn);
    opt.text = fullText;
    opt.icon = btn->icon();
    opt.iconSize = btn->iconSize();

    QRect cr = btn->style()->subElementRect(QStyle::SE_PushButtonContents, &opt, btn);
    int avail = cr.width();
    if (avail < 8)
        avail = qMax(8, btn->width() - 16);

    const QFontMetrics fm(btn->font());
    const QString elided = fm.elidedText(fullText, Qt::ElideRight, avail);
    btn->setText(elided);
    btn->setToolTip(elided != fullText ? fullText : QString());
    return;
}

void AiServiceDialog::refreshButtonElide()
{
    elidePushButtonText(cancelButton, m_cancelButtonFullText);
    elidePushButtonText(goButton, m_goButtonFullText);
    return;
}

int AiServiceDialog::getLabelHeight(QLabel *label)
{
    int lineCount = 1;
    QRect textRect = label->contentsRect();
    QFontMetrics fm(label->font());

    QString text = label->text();
    QRect neededRect = fm.boundingRect(textRect,
                                      Qt::TextWordWrap | label->alignment(),
                                      text);

    lineCount = (neededRect.height() + 1) / fm.height();
    return lineCount * fm.height();
}

void AiServiceDialog::updateFixedSize()
{
    int realHeight = 152;
    int tipHeight = getLabelHeight(titleLabel);
    int infoHeight = getLabelHeight(detailLabel);

    KyInfo() << "======tipHeight======" << tipHeight;
    KyInfo() << "======infoHeight======" << infoHeight;
    realHeight += tipHeight + infoHeight;
    setFixedSize(452, realHeight);

    return;
}

void AiServiceDialog::applyFont(const qreal fontSize, const QString &fontFamily)
{
    if (fontSize <= 0)
        return;

    KyInfo() << "fontSize" << fontSize << "fontFamily" <<  fontFamily;
    QFont baseFont;
    baseFont.setPointSize(fontSize);
    if (!fontFamily.isEmpty()) {
        baseFont.setFamily(fontFamily);
    }

    detailLabel->setFont(baseFont);

    QFont titleFont = baseFont;
    titleFont.setBold(true);
    titleLabel->setFont(titleFont);

    cancelButton->setFont(baseFont);
    goButton->setFont(baseFont);

    updateFixedSize();
    refreshButtonElide();
    moveToCenter();
    return;
}

QScreen *AiServiceDialog::getCurrentScreen()
{
#ifdef UKUI_WINDOWHELPER_SUPPORT
    UkuiWindowHelper *ukuiWindowHelper = new UkuiWindowHelper(this);
    return ukuiWindowHelper->getCurrentScreenBlocking();
#else
    return QGuiApplication::screenAt(QCursor::pos());
#endif

}

void AiServiceDialog::moveToCenter()
{
    QScreen *screen = getCurrentScreen();
    if (screen == nullptr || screen->availableGeometry().isEmpty()) {
        screen = QGuiApplication::primaryScreen();
    }

    if (screen == nullptr || screen->availableGeometry().isEmpty()) {
        return;
    }

    QRect screenRect = screen->availableGeometry();
    KyInfo() << "====currentScreen====name" << screen->name();
    KyInfo() << "====availableGeometry====x:" << screenRect.x() << "y:" << screenRect.y()
             << "width:" << screenRect.width() << "height:" << screenRect.height()
             << "dialog width:" << screenRect.width() << "dialog height:" << screenRect.height();

    int x = screenRect.x() + (screenRect.width() - this->width()) / 2;
    int y = screenRect.y() + (screenRect.height() - this->height()) / 2;
    this->move(x, y);
    KyInfo() << "====moveToCenter====x:" << x << "y:" << y;
    return;
}
