/* -*- 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 "changeusernickname.h"

#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QMouseEvent>
#include <QKeyEvent>
#include <QDebug>

#include <QDBusInterface>
#include <QDBusReply>

#include <QPainter>
#include <QPainterPath>

#include <glib.h>

#define NICKNAME_LENGTH 32

extern void qt_blurImage(QImage &blurImage, qreal radius, bool quality, int transposed);

ChangeUserNickname::ChangeUserNickname(QString nn, QStringList ns, QString op, QWidget *parent) :
    KDialog(parent),
    namesIsExists(ns),
    realname(nn)
{
    this->setFixedSize(QSize(480, 254));
    this->setWindowTitle(tr("Set Nickname"));
    this->setWindowIcon("ukui-control-center");

    cniface = new QDBusInterface("org.freedesktop.Accounts",
                                  op,
                                  "org.freedesktop.Accounts.User",
                                  QDBusConnection::systemBus());


    initUI();
    setConnect();
}

ChangeUserNickname::~ChangeUserNickname()
{
    delete cniface;
}

void ChangeUserNickname::initUI()
{
    //用户名
    userNameLabel = new QLabel();
    userNameLabel->setFixedWidth(100);
    setTextDynamicInNick(userNameLabel, tr("UserName"));

    userNameLineEdit = new QLineEdit();
    userNameLineEdit->setFixedSize(QSize(300, 36));
    userNameLineEdit->setPlaceholderText(QString(g_get_user_name()));
    userNameLineEdit->setReadOnly(true);
    userNameLineEdit->setFocusPolicy(Qt::NoFocus);

    userNameHorLayout = new QHBoxLayout;
    userNameHorLayout->setSpacing(25);
    userNameHorLayout->setContentsMargins(0, 0, 0, 0);
    userNameHorLayout->addWidget(userNameLabel);
    userNameHorLayout->addWidget(userNameLineEdit);

    //用户昵称
    nickNameLabel = new QLabel();
    nickNameLabel->setFixedWidth(100);
    setTextDynamicInNick(nickNameLabel, tr("NickName"));

    tipLabel = new QLabel();
    QFont ft;
    ft.setPixelSize(14);
    tipLabel->setFont(ft);
    tipLabel->setFixedSize(QSize(300, 36));
    tipLabel->setStyleSheet("color:red;");

    nickNameLineEdit = new QLineEdit(this);
    nickNameLineEdit->setFocus();
    nickNameLineEdit->setFixedSize(QSize(300, 36));
    nickNameLineEdit->setText(realname);

    nickNameHorLayout = new QHBoxLayout;
    nickNameHorLayout->setSpacing(25);
    nickNameHorLayout->setContentsMargins(0, 0, 0, 0);
    nickNameHorLayout->addWidget(nickNameLabel);
    nickNameHorLayout->addWidget(nickNameLineEdit);

    tipHorLayout = new QHBoxLayout;
    tipHorLayout->setSpacing(0);
    tipHorLayout->setContentsMargins(0, 0, 0, 0);
    tipHorLayout->addStretch();
    tipHorLayout->addWidget(tipLabel);

    nickNameWithTipVerLayout = new QVBoxLayout;
    nickNameWithTipVerLayout->setSpacing(4);
    nickNameWithTipVerLayout->setContentsMargins(0, 0, 0, 0);
    nickNameWithTipVerLayout->addLayout(nickNameHorLayout);
    nickNameWithTipVerLayout->addLayout(tipHorLayout);

    //中部输入区域
    contentVerLayout = new QVBoxLayout;
    contentVerLayout->setSpacing(24);
    contentVerLayout->setContentsMargins(0, 0, 0, 0);
    contentVerLayout->addLayout(userNameHorLayout);
    contentVerLayout->addLayout(nickNameWithTipVerLayout);
    contentVerLayout->addStretch();

    //底部“取消”、“确定”按钮
    cancelBtn = new QPushButton();
    cancelBtn->setMinimumWidth(96);
    cancelBtn->setText(tr("Cancel"));
    cancelBtn->setProperty("useButtonPalette", true);
    confirmBtn = new QPushButton();
    confirmBtn->setMinimumWidth(96);
    confirmBtn->setText(tr("Confirm"));
    confirmBtn->setProperty("isImportant", true);

    bottomBtnsHorLayout = new QHBoxLayout;
    bottomBtnsHorLayout->setSpacing(16);
    bottomBtnsHorLayout->setContentsMargins(0, 0, 0, 0);
    bottomBtnsHorLayout->addStretch();
    bottomBtnsHorLayout->addWidget(cancelBtn);
    bottomBtnsHorLayout->addWidget(confirmBtn);

    //主布局
    mainVerLayout = new QVBoxLayout;
    mainVerLayout->setContentsMargins(24, 24, 24, 24);
    mainVerLayout->addLayout(contentVerLayout);
    mainVerLayout->addStretch();
    mainVerLayout->addLayout(bottomBtnsHorLayout);

    mainWidget()->setLayout(mainVerLayout);

}

void ChangeUserNickname::setConnect()
{
    connect(nickNameLineEdit, &QLineEdit::textEdited, this, [=](QString txt){
        nameLegalityCheck(txt);
        refreshConfirmBtnStatus();
    });

    connect(confirmBtn, &QPushButton::clicked, this, [=]{
        cniface->call("SetRealName", nickNameLineEdit->text());
        close();
    });

    connect(cancelBtn, &QPushButton::clicked, this, [=]{
        close();
    });
}

void ChangeUserNickname::nameLegalityCheck(QString nickname)
{
    if (nickname.isEmpty()){
        tipString = tr("NickName's length must between 1~%1 characters").arg(NICKNAME_LENGTH);
    } else if (namesIsExists.contains(nickname)){
        tipString = tr("nickName already in use.");
    } else if (nickNameLineEdit->text().contains(":")) {
        tipString = tr("Can't contains ':'.");
    } else if(nickname.length() > NICKNAME_LENGTH) {
        nickNameLineEdit->setText(oldNickName);
    } else {
        oldNickName = nickname;
        tipString = tr("");
    }

    setTextDynamicInNick(tipLabel, tipString);

    refreshConfirmBtnStatus();

}

void ChangeUserNickname::refreshConfirmBtnStatus()
{
    if (!tipLabel->text().isEmpty() || nickNameLineEdit->text().isEmpty()) {
        confirmBtn->setEnabled(false);
    } else {
        confirmBtn->setEnabled(true);
    }
}

void ChangeUserNickname::setupStatus(){
    tipLabel->hide();
}

bool ChangeUserNickname::setTextDynamicInNick(QLabel *label, QString string){

    bool isOverLength = false;
    QFontMetrics fontMetrics(label->font());
    int fontSize = fontMetrics.width(string);

    QString str = string;
    int pSize = label->width();
    if (fontSize > pSize) {
        str = fontMetrics.elidedText(string, Qt::ElideRight, pSize);
        label->setToolTip(string);
        isOverLength = true;
    } else {
        label->setToolTip("");
    }
    label->setText(str);
    return isOverLength;

}

void ChangeUserNickname::keyPressEvent(QKeyEvent * event){
    switch (event->key())
    {
    case Qt::Key_Enter:
        if (confirmBtn->isEnabled())
            confirmBtn->clicked();
        break;
    case Qt::Key_Return:
        if (confirmBtn->isEnabled())
            confirmBtn->clicked();
        break;
    default:
        QDialog::keyPressEvent(event);
    }
}


bool ChangeUserNickname::eventFilter(QObject *watched, QEvent *event)
{
    if (event->type() == QEvent::MouseButtonPress){
        QMouseEvent * mouseEvent = static_cast<QMouseEvent *>(event);
        if (mouseEvent->button() == Qt::LeftButton ){
            if (watched == nickNameLineEdit){
                if (QString::compare(nickNameLineEdit->text(), g_get_real_name()) == 0){
                    nickNameLineEdit->setText("");
                    refreshConfirmBtnStatus();
                }
            }
        }
    }

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

