/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 *
 * Copyright (C) 2024 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 2 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, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 */
#include "utilsforuserinfo.h"

#include <QFrame>
#include <QPushButton>
#include <QLabel>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QDebug>
#include <QMenu>

#include "elipsemaskwidget.h"

#ifdef signals
#undef signals
#endif

#include <glib.h>
#include <gio/gio.h>

UtilsForUserinfo::UtilsForUserinfo(QObject *parent) : QObject(parent)
{
    m_isServerVersion = UkccCommon::isServerVersion();
    m_isExistMfa = UkccCommon::isExistMfa();

    initUI();

    initConnections();
}

void UtilsForUserinfo::initUI()
{
    m_pMainItemFrame = new UkccFrame(nullptr, UkccFrame::Top, true);

    logoBtn = new QPushButton();
    logoBtn->setFixedSize(QSize(50, 50));
    logoBtn->setIconSize(QSize(48, 48));
    logoBtn->setObjectName("logo");

    nickNameLabel = new QLabel();
    nickNameLabel->setFixedHeight(26);

    typeLabel = new QLabel();
    typeLabel->setFixedHeight(20);

    changePwdBtn = new QPushButton();
    changePwdBtn->setText(tr("Password"));
    changePwdBtn->setObjectName("Password");
    changeTypeBtn = new QPushButton();
    changeTypeBtn->setText(tr("Type"));
    changeTypeBtn->setObjectName("Type");
    delUserBtn = new QPushButton();
    delUserBtn->setText(tr("Delete"));
    delUserBtn->setObjectName("Delete");

    m_pMoreBtn = new QToolButton();
    m_pMoreBtn->setStyleSheet("QToolButton:!checked{background-color: palette(base)}");
    m_pMoreBtn->setProperty("useButtonPalette", true);
    m_pMoreBtn->setPopupMode(QToolButton::InstantPopup);
    m_pMoreBtn->setIcon(QIcon::fromTheme("view-more-horizontal-symbolic"));
    QMenu *pMenu = new QMenu(m_pMoreBtn);
    m_pMoreBtn->setMenu(pMenu);
    m_pChangePwdAct = new QAction(tr("Password"),this);
    m_pChangeTypeAct = new QAction(tr("Type"),this);
    m_pDeleteAct = new QAction(tr("Delete"),this);
    m_pBindOtpAct = new QAction(tr("Bind OTP Dynamic Password"),this);
    m_pBindUkeyAct = new QAction(tr("Bind Security Password"),this);
    pMenu->addAction(m_pChangePwdAct);
    pMenu->addAction(m_pChangeTypeAct);
    pMenu->addAction(m_pBindOtpAct);
    pMenu->addAction(m_pBindUkeyAct);
    pMenu->addAction(m_pDeleteAct);
}

void UtilsForUserinfo::initConnections()
{
    connect(changePwdBtn, &QPushButton::clicked, this, [=]{
        UkccCommon::buriedSettings(QString("UtilsForUserinfo"), changePwdBtn->objectName(), QString("settings"));

        emit changePwdBtnPressed();
    });
    connect(changeTypeBtn, &QPushButton::clicked, this, [=]{
        UkccCommon::buriedSettings(QString("UtilsForUserinfo"), changeTypeBtn->objectName(), QString("settings"));

        emit changeTypeBtnPressed();
    });
    connect(logoBtn, &QPushButton::clicked, this, [=]{
        UkccCommon::buriedSettings(QString("UtilsForUserinfo"), logoBtn->objectName(), QString("settings"));

        emit changeLogoBtnPressed();
    });
    connect(delUserBtn, &QPushButton::clicked, this, [=]{
        UkccCommon::buriedSettings(QString("UtilsForUserinfo"), delUserBtn->objectName(), QString("settings"));

        emit deleteUserBtnPressed();
    });

    connect(m_pChangePwdAct, &QAction::triggered, this, [=](){
        UkccCommon::buriedSettings(QString("UtilsForUserinfo"), m_pChangePwdAct->objectName(), QString("settings"));

        emit changePwdBtnPressed();
    });

    connect(m_pChangeTypeAct, &QAction::triggered, this, [=](){
        UkccCommon::buriedSettings(QString("UtilsForUserinfo"), m_pChangeTypeAct->objectName(), QString("settings"));

        emit changeTypeBtnPressed();
    });

    connect(m_pDeleteAct, &QAction::triggered, this, [=](){
        UkccCommon::buriedSettings(QString("UtilsForUserinfo"), m_pDeleteAct->objectName(), QString("settings"));

        emit deleteUserBtnPressed();
    });

    connect(m_pBindOtpAct, &QAction::triggered, this, [=](){
        UkccCommon::buriedSettings(QString("UtilsForUserinfo"), m_pBindOtpAct->objectName(), QString("settings"));

        emit bindOtpActPressed();
    });
    connect(m_pBindUkeyAct, &QAction::triggered, this, [=](){
        UkccCommon::buriedSettings(QString("UtilsForUserinfo"), m_pBindUkeyAct->objectName(), QString("settings"));

        emit bindUkeyActPressed();
    });
}

UkccFrame * UtilsForUserinfo::buildItemForUsers()
{
    //圆形头像遮罩
    logoBtn->setProperty("isRoundButton", true);

    subUserInfoVerLayout = new QVBoxLayout();
    subUserInfoVerLayout->setSpacing(0);
    subUserInfoVerLayout->setContentsMargins(0, 0, 0, 0);
//    subUserInfoVerLayout->addStretch();
    subUserInfoVerLayout->addWidget(nickNameLabel, Qt::AlignHCenter);
    subUserInfoVerLayout->addWidget(typeLabel, Qt::AlignHCenter);
//    subUserInfoVerLayout->addStretch();

    mUserInfoHorLayout = new QHBoxLayout();
    mUserInfoHorLayout->setSpacing(8);
    mUserInfoHorLayout->setContentsMargins(16, 0, 16, 0);
    mUserInfoHorLayout->addWidget(logoBtn);
    mUserInfoHorLayout->addLayout(subUserInfoVerLayout);
    mUserInfoHorLayout->addStretch();
    mUserInfoHorLayout->addWidget(changePwdBtn);
    QFrame *line1 = createVLine(m_pMainItemFrame, 10);
    mUserInfoHorLayout->addWidget(line1);
    mUserInfoHorLayout->addWidget(changeTypeBtn);
    QFrame *line2 = createVLine(m_pMainItemFrame, 10);
    mUserInfoHorLayout->addWidget(line2);
    mUserInfoHorLayout->addWidget(delUserBtn);
    mUserInfoHorLayout->addWidget(m_pMoreBtn);

    if (m_isExistMfa) {
        if (m_isServerVersion) {
            if (!getuid()) {
                changePwdBtn->hide();
                line1->hide();
                changeTypeBtn->hide();
                line2->hide();
                delUserBtn->hide();
            } else {
                m_pMoreBtn->hide();
            }
        } else {
            changePwdBtn->hide();
            line1->hide();
            changeTypeBtn->hide();
            line2->hide();
            delUserBtn->hide();
        }
    } else {
        m_pMoreBtn->hide();
    }


    mainUserVerLayout = new QVBoxLayout();
    mainUserVerLayout->setSpacing(0);
    mainUserVerLayout->setContentsMargins(0, 0, 0, 0);
    mainUserVerLayout->addLayout(mUserInfoHorLayout);

    m_pMainItemFrame->setRadiusType(UkccFrame::Top);
    m_pMainItemFrame->setLayout(mainUserVerLayout);

    return m_pMainItemFrame;
}

void UtilsForUserinfo::refreshUserLogo(QString logo)
{
    QPixmap iconfile = makeRoundLogo(logo, logoBtn->width(), logoBtn->height(), logoBtn->width()/2);
    logoBtn->setIcon(iconfile);
}

void UtilsForUserinfo::refreshUserNickname(QString name)
{
    if (setUtilsTextDynamic(nickNameLabel, name)) {
        nickNameLabel->setToolTip(name);
    }
}

void UtilsForUserinfo::refreshUserType(int type)
{
    QString t = _accountTypeIntToString(type);
    typeLabel->setText(t);
}

void UtilsForUserinfo::refreshDelStatus(bool enabled)
{
    if (m_isExistMfa) {
        if (m_isServerVersion) {
            if (!getuid()) {
                m_pDeleteAct->setEnabled(enabled);
            } else {
                delUserBtn->setEnabled(enabled);
            }
        } else {
            m_pDeleteAct->setEnabled(enabled);
        }
    } else {
        delUserBtn->setEnabled(enabled);
    }
}

void UtilsForUserinfo::refreshPwdStatus(bool enabled)
{
    if (m_isExistMfa) {
        if (m_isServerVersion) {
            if (!getuid()) {
                m_pChangePwdAct->setEnabled(enabled);
            } else {
                changePwdBtn->setEnabled(enabled);
            }
        } else {
            m_pChangePwdAct->setEnabled(enabled);
        }
    } else {
        changePwdBtn->setEnabled(enabled);
    }
}

void UtilsForUserinfo::refreshTypeStatus(bool enabled)
{
    if (m_isExistMfa) {
        if (m_isServerVersion) {
            if (!getuid()) {
                m_pChangeTypeAct->setEnabled(enabled);
            } else {
                changeTypeBtn->setEnabled(enabled);
            }
        } else {
            m_pChangeTypeAct->setEnabled(enabled);
        }
    } else {
        changeTypeBtn->setEnabled(enabled);
    }
}

void UtilsForUserinfo::setMoreBtnVisible(bool visible)
{
    // 不存kylin-mfa或者服务器版本非root用户无更多设置按钮，不可设置为可见
    if (!m_isExistMfa || (m_isServerVersion && getuid())) {
        return;
    }

    m_pMoreBtn->setVisible(visible);

}

void UtilsForUserinfo::setDelVisible(bool visible)
{
    if (m_isExistMfa) {
        if (m_isServerVersion) {
            if (!getuid()) {
                m_pDeleteAct->setVisible(visible);
            } else {
                delUserBtn->setVisible(visible);
            }
        } else {
            m_pDeleteAct->setVisible(visible);
        }
    } else {
        delUserBtn->setVisible(visible);
    }
}

void UtilsForUserinfo::setPwdVisible(bool visible)
{
    if (m_isExistMfa) {
        if (m_isServerVersion) {
            if (!getuid()) {
                m_pChangePwdAct->setVisible(visible);
            } else {
                changePwdBtn->setVisible(visible);
            }
        } else {
            m_pChangePwdAct->setVisible(visible);
        }
    } else {
        changePwdBtn->setVisible(visible);
    }
}

void UtilsForUserinfo::setTypeVisible(bool visible)
{
    if (m_isExistMfa) {
        if (m_isServerVersion) {
            if (!getuid()) {
                m_pChangeTypeAct->setVisible(visible);
            } else {
                changeTypeBtn->setVisible(visible);
            }
        } else {
            m_pChangeTypeAct->setVisible(visible);
        }
    } else {
        changeTypeBtn->setVisible(visible);
    }
}

void UtilsForUserinfo::setObjectPathData(QString op)
{
    m_pMainItemFrame->setObjectName(op);
}

bool UtilsForUserinfo::setUtilsTextDynamic(QLabel *label, QString string)
{
    bool isOverLength = false;
    QFontMetrics fontMetrics(label->font());
    int fontSize = fontMetrics.horizontalAdvance(string);

    QString str = string;
    if (fontSize > 80) {
        label->setFixedWidth(80);
        str = fontMetrics.elidedText(string, Qt::ElideRight, 80);
        isOverLength = true;
    } else {
        label->setFixedWidth(fontSize);
    }
    label->setText(str);
    return isOverLength;
}

QFrame * UtilsForUserinfo::createHLine(QFrame *f, int len)
{
    QFrame *line = new QFrame(f);
    if (len == 0){
        line->setMinimumSize(QSize(0, 1));
        line->setMaximumSize(QSize(16777215, 1));
    } else {
        line->setMinimumSize(QSize(len, 1));
        line->setMaximumSize(QSize(len, 1));
    }

    line->setLineWidth(0);
    line->setFrameShape(QFrame::HLine);
    line->setFrameShadow(QFrame::Sunken);
    return line;
}

QFrame * UtilsForUserinfo::createVLine(QFrame *f, int len)
{
    QFrame *line = new QFrame(f);
    if (len == 0){
        line->setMinimumSize(QSize(1, 0));
        line->setMaximumSize(QSize(1, 16777215));
    } else {
        line->setMinimumSize(QSize(1, len));
        line->setMaximumSize(QSize(1, len));
    }

    line->setLineWidth(0);
    line->setFrameShape(QFrame::VLine);
    line->setFrameShadow(QFrame::Sunken);
    return line;
}

void UtilsForUserinfo::userPropertyChangedSlot(QString property, QMap<QString, QVariant> propertyMap, QStringList propertyList)
{
    Q_UNUSED(property);
    Q_UNUSED(propertyList);

    if (propertyMap.keys().contains("IconFile")){
        QString current = propertyMap.value("IconFile").toString();

        refreshUserLogo(current);
    }

    if (propertyMap.keys().contains("AccountType")){
        int current = propertyMap.value("AccountType").toInt();

        refreshUserType(current);
    }

}

QString UtilsForUserinfo::_accountTypeIntToString(int type)
{
    QString atype;
    if (type == 0)
        atype = tr("Standard");
    else if (type == 1)
        atype = tr("Admin");

    return atype;
}

QPixmap UtilsForUserinfo::makeRoundLogo(QString logo, int wsize, int hsize, int radius)
{
    QPixmap rectPixmap;
    QPixmap iconcop = QPixmap(logo);

    if (iconcop.width() > iconcop.height()) {
        QPixmap iconPixmap = iconcop.copy((iconcop.width() - iconcop.height())/2, 0, iconcop.height(), iconcop.height());
        // 根据label高度等比例缩放图片
        rectPixmap = iconPixmap.scaledToHeight(hsize);
    } else {
        QPixmap iconPixmap = iconcop.copy(0, (iconcop.height() - iconcop.width())/2, iconcop.width(), iconcop.width());
        // 根据label宽度等比例缩放图片
        rectPixmap = iconPixmap.scaledToWidth(wsize);
    }

    if (rectPixmap.isNull()) {
        return QPixmap();
    }
    QPixmap pixmapa(rectPixmap);
    QPixmap pixmap(radius*2,radius*2);
    pixmap.fill(Qt::transparent);
    QPainter painter(&pixmap);
    painter.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
    QPainterPath path;
    path.addEllipse(0, 0, radius*2, radius*2);
    painter.setClipPath(path);
    painter.drawPixmap(0, 0, radius*2, radius*2, pixmapa);
    return pixmap;
}
