/* usersview.cpp
 * Copyright (C) 2018 Tianjin KYLIN Information Technology 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, 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 "usersview.h"
#include "hoverwidget.h"
#include <QListWidget>
#include <QDebug>
#include <QApplication>
#include <QDesktopWidget>
#include <QScreen>
#include <QAction>
#include <QPixmap>
#include <QPainter>
#include <QPainterPath>
#include <QWidgetAction>
#include <QLayout>
#include <QPushButton>
#include <QKeyEvent>
#include <QStandardPaths>
#include <QDateTime>
#include <QCoreApplication>
#include <QLightDM/UsersModel>
#include <QPropertyAnimation>
#include <unistd.h>
#include <QGraphicsOpacityEffect>
#include "xeventmonitor.h"
#include "globalv.h"
#include "securityuser.h"
#include "ktooltip.h"
#include "greeterutils.h"

/*记录五个节点的坐标*/
#define ARROW_WIDTH 120*scale
#define LEFT_ARROW_X 0
#define ITEM1_X (ARROW_WIDTH)
#define ITEM2_X (ITEM1_X + CENTER_ENTRY_WIDTH * 2 - ENTRY_WIDTH)
#define ITEM3_X (ITEM2_X + CENTER_ENTRY_WIDTH * 2 - ENTRY_WIDTH )
#define ITEM4_X (ITEM3_X + CENTER_ENTRY_WIDTH*3 - ENTRY_WIDTH*2)
#define ITEM5_X (ITEM4_X + CENTER_ENTRY_WIDTH * 2 - ENTRY_WIDTH)
#define RIGHT_ARROW_X (CENTER_ENTRY_WIDTH*9 - ENTRY_WIDTH*4 + 220*scale)
#define ITEM_Y CENTER_ENTRY_HEIGHT-ENTRY_HEIGHT
#define ITEM_CENTER_Y  0

UsersView::UsersView(QWidget *parent) :
    QWidget(parent),
    usersModel(nullptr),
    currentUser(-1),
    prevArrow(nullptr),
    nextArrow(nullptr),
    secUser(SecurityUser::instance()),
    lasttime(QTime::currentTime()),
    mouseClickLast(QTime::currentTime())
{
    setFocusPolicy(Qt::NoFocus);
    connect(XEventMonitor::instance(), SIGNAL(keyPress(const QString &)),
            this, SLOT(onGlobalKeyRelease(const QString &)));

    setAttribute(Qt::WA_TranslucentBackground);

}

UsersView::~UsersView()
{
}

void UsersView::resizeEvent(QResizeEvent *)
{
    //setCurrentRow(currentUser);
}

bool UsersView::eventFilter(QObject *obj, QEvent *event)
{
    for(int i = 0; i<nameList.count();i++){
        if(obj->objectName() == nameList.at(i)){
            if(event->type() == 110){
                QFontMetrics fontMetrics(font());
                if(fontMetrics.width(nameList.at(i)) > textlabel->width()){
                    Q_EMIT setKToolTip(nameList.at(i));
                }
            } else if (event->type() == 11){
                Q_EMIT hideKTooltip();
            }
        }
    }
    return false;
}

void UsersView::setModel(QAbstractListModel *model)
{
    usersModel = model;
    connect(usersModel, &QAbstractListModel::rowsInserted, this, &UsersView::onUserAdded);
    connect(usersModel, &QAbstractListModel::rowsRemoved, this, &UsersView::onUserRemoved);
    connect(usersModel, &QAbstractListModel::dataChanged, this, &UsersView::onUserChanged);

    for(int i = 0; i < usersModel->rowCount(); i++){
        QString name = usersModel->index(i).data(QLightDM::UsersModel::NameRole).toString();
        if(secUser->isSecrityUser(name))
            insertUserEntry(i);
    }

}

void UsersView::setCurrentUser(const QString &userName, bool entered)
{
    int x = 0;
    for(x = 0; x < usersModel->rowCount(); x++)
    {
       QString name= usersModel->index(x).data(QLightDM::UsersModel::NameRole).toString();
       for(int i = 0;i < list.count(); i++){
           if(list.at(i)->objectName() == userName + "1"){
               list.at(i)->setStyleSheet("HoverWidget{background-color:rgb(255,255,255,40%);border-radius: 6px;}"
                                         "HoverWidget:hover:!pressed{background-color:rgb(255,255,255,40%);border-radius: 6px;}");
               nowAt = i;
           } else {
               list.at(i)->setStyleSheet("HoverWidget{background-color:transparent;}"
                                         "HoverWidget:hover:!pressed{background-color:rgb(255,255,255,15%);border-radius: 6px;}");
           }
       }
       if(userName == name)
            break;
    }

    QModelIndex index = usersModel->index(x, 0);
    Q_EMIT currentUserChanged(index);
    Q_EMIT userSelected(index);
    QString strRealName= index.data(QLightDM::UsersModel::RealNameRole).toString();
    if (strRealName.isEmpty())
        strRealName = userName;
    if(nameList.contains(strRealName)){
        return ;
    }
    Q_EMIT userNotFound(userName);
}

void UsersView::onGlobalKeyRelease(const QString &key)
{

}

void UsersView::showEvent(QShowEvent *event)
{

    QWidget::showEvent(event);
}

void UsersView::onShowUsermenu()
{
    usersMenu->show();
}

void UsersView::insertUserEntry(int row)
{
//    QModelIndex index = usersModel->index(row, 0);
//    QPersistentModelIndex persistentIndex(index);
//    UserEntry *entry = new UserEntry(this);
//    entry->setUserIndex(persistentIndex);
//    entry->installEventFilter(this);

//    entry->hide();

//    userlist.append(entry);
    if(!usersMenu){
        usersMenu = new QMenu(this);
        usersMenu->setWindowFlags(Qt::X11BypassWindowManagerHint);
        usersMenu->setToolTipsVisible(true);
        connect(usersMenu, &QMenu::triggered,
                       this, &UsersView::onUserMenuTrigged);

    }

    QString realName = usersModel->index(row,0).data(QLightDM::UsersModel::RealNameRole).toString();
    QString userName = usersModel->index(row,0).data(QLightDM::UsersModel::NameRole).toString();
    if(realName.isEmpty())
        realName = userName;

    QString iconPath = usersModel->index(row,0).data(QLightDM::UsersModel::ImagePathRole).toString();
    if(!QFile(iconPath).exists())
    {
        iconPath = UKUIGreeter::Utils::getDefaultFace();
    }

    QWidgetAction *action = new QWidgetAction(usersMenu);
    action->setData(userName);

    HoverWidget *widget = new HoverWidget("");
    widget->setStyleSheet("HoverWidget:hover{background-color:rgb(255,255,255,15%);border-radius: 6px;}");
    widget->setObjectName(userName+ "1");
    list.append(widget);
    widget->setFixedSize(240, 40);
    QLabel *iconlabel =new QLabel(widget);
    QPixmap p(iconPath);
    p = p.scaled(32*scale,32*scale, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    p = PixmapToRound(p, 16*scale);
    iconlabel->setPixmap(p);
    iconlabel->setGeometry(8,4,32,32);
    textlabel =new KTipLabel(widget);
    textlabel->installEventFilter(this);
    textlabel->setStyleSheet("QToolTip{border-radius:4px;background-color:#FFFFFF;color:black;}");
    textlabel->setGeometry(48,8,190,24);
    if(getLoginStaus(userName)){
        QLabel *statusIcon = new QLabel(widget);
        QPixmap status(":/images/selected.svg");
        status = status.scaled(14*scale,14*scale, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
        p = PixmapToRound(status, 7*scale);
        statusIcon->setPixmap(status);
        statusIcon->setGeometry(32, 5, 14, 14);
    }
    action->setDefaultWidget(widget);

    textlabel->setObjectName(realName);
    nameList.append(textlabel->objectName());
    textlabel->setText(realName);
    usersMenu->addAction(action);
    usersMenu->adjustSize();
}

QPixmap UsersView::PixmapToRound(const QPixmap &src, int radius)
{
    if (src.isNull()) {
        return QPixmap();
    }
    QPixmap pixmapa(src);
    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;
}

void UsersView::onUserMenuTrigged(QAction *action)
{
    QString userName = action->data().toString();
    int x = 0;
    for(x = 0; x < usersModel->rowCount(); x++)
    {
       QString name= usersModel->index(x).data(QLightDM::UsersModel::NameRole).toString();
        if(userName == name){
            break;
        }
    }

    for (int i =0;i<list.count(); i++)
    {
        if(list.at(i)->objectName() == userName + "1"){
            list.at(i)->setStyleSheet("HoverWidget{background-color:rgb(255,255,255,40%);border-radius: 6px;}"
                                      "HoverWidget:hover:!pressed{background-color:rgb(255,255,255,40%);border-radius: 6px;}");
            nowAt = i;
        } else {
            list.at(i)->setStyleSheet("HoverWidget{background-color:transparent;}"
                                      "HoverWidget:hover:!pressed{background-color:rgb(255,255,255,15%);border-radius: 6px;}");
        }
    }
    qDebug()<<"ddd"<<nowAt<<x;
    QModelIndex index = usersModel->index(x, 0);
    Q_EMIT currentUserChanged(index);
    Q_EMIT userSelected(index);
}

void UsersView::removeUserEntry(int row)
{

}

void UsersView::onUserAdded(const QModelIndex &parent, int left, int right)
{
    Q_UNUSED(parent);

    for(int i = left; i <= right; i++){
        QString name = usersModel->index(i).data(QLightDM::UsersModel::NameRole).toString();
        if(secUser->isSecrityUser(name))
            insertUserEntry(i);
    }
}

void UsersView::onUserRemoved(const QModelIndex &parent, int left, int right)
{
    Q_UNUSED(parent);

    for(int i = left; i <= right; i++){
        removeUserEntry(i);
    }
}

void UsersView::onUserChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
{
//    int left = topLeft.row();
//    int right = bottomRight.row();

//    for(int i = left;i<=right;i++)
//    {
//        QModelIndex index = usersModel->index(i,0);
//        uid_t uid =  index.data(QLightDM::UsersModel::UidRole).toUInt();
//        for(int j = 0;j<userlist.count();j++)
//        {
//            UserEntry *entry = userlist.at(j);
//            uid_t id = entry->userIndex().data(QLightDM::UsersModel::UidRole).toUInt();
//            if(id == uid)
//            {
//                entry->setUserName(index.data(Qt::DisplayRole).toString());
//                entry->setFace(index.data(QLightDM::UsersModel::ImagePathRole).toString());
//                entry->setLogin(index.data(QLightDM::UsersModel::LoggedInRole).toBool());
//                break;
//            }
//        }
//    }
}

bool UsersView::getIsUser(QString username)
{
    for(int i = 0; i < usersModel->rowCount(); i++){
        QString name = usersModel->index(i).data(QLightDM::UsersModel::NameRole).toString();
    	if(name == username)
	    return true;
    }
    return false;
}

bool UsersView::getLoginStaus(QString username)
{
    for(int i = 0; i < usersModel->rowCount(); i++){
        QString name = usersModel->index(i).data(QLightDM::UsersModel::NameRole).toString();
        if(name == username){
 	    return usersModel->index(i).data(QLightDM::UsersModel::LoggedInRole).toBool();	
	}
    }
}

void UsersView::setCurrentRow(int user)
{

//    if(userlist.count() == 0)
//        return ;

//    if(user < 0 || user >= userlist.count())
//        user = 0;

    if(usersMenu->actions().count() == 0)
        return ;

    if(user < 0 || user >= usersMenu->actions().count())
        user = 0;

    currentUser = user;

    for (int i =0;i<list.count(); i++)
    {
        if(list.at(i)->objectName() == user + "1"){
            list.at(i)->setStyleSheet("HoverWidget{background-color:rgb(255,255,255,40%);border-radius: 6px;}"
                                      "HoverWidget:hover:!pressed{background-color:rgb(255,255,255,40%);border-radius: 6px;}");
            nowAt = i;
        } else {
            list.at(i)->setStyleSheet("HoverWidget{background-color:transparent;}"
                                      "HoverWidget:hover:!pressed{background-color:rgb(255,255,255,15%);border-radius: 6px;}");
        }
    }

    usersMenu->adjustSize();
//    for(int i = 0;i<userlist.count();i++){
//        int x = 0,y = 0;
//        x = i % 7;
//        y = i / 7;
//        userlist.at(i)->setGeometry(x*(ENTRY_WIDTH + C_BORDER_WIDTH),y*(ENTRY_HEIGHT + C_BORDER_HEIGHT),ENTRY_WIDTH,ENTRY_HEIGHT);
//        userlist.at(i)->show();
//    }

    //获取当前用户对应的model下标
//    UserEntry *entry = userlist.at(currentUser);
//    uid_t uid =  entry->userIndex().data(QLightDM::UsersModel::UidRole).toUInt();

//    QAction *action = usersMenu->actions()
//    int x = 0;
//    for(x = 0; x < usersModel->rowCount(); x++)
//    {
//        uid_t id= usersModel->index(x).data(QLightDM::UsersModel::UidRole).toUInt();
//        if(uid == id)
//            break;
//    }

    QModelIndex index = usersModel->index(user, 0);
    Q_EMIT currentUserChanged(index);
    Q_EMIT userSelected(index);


}

void UsersView::keyBdRelease(QString key)
{
    QString focus = "focus";
    QString normal = "normal";
    if(key == "Up"){
//        if(nowAt == -1){
//            nowAt = 0;
//            setButtonStyle(focus);
//        }
        for(int i = 0; i < list.count(); i++){
            if(nowAt == i){
                if(i == 0)
                    return ;
                qDebug()<<"enheng???000"<<list.count()<< "llllllll i ="<<i;
                list.at(i)->setStyleSheet("HoverWidget{background-color:transparent;}"
                                                      "HoverWidget:hover:!pressed{background-color:rgb(255,255,255,15%);border-radius: 6px;}");
                list.at(i-1)->setStyleSheet("HoverWidget{background-color:rgb(255,255,255,40%);border-radius: 6px;}"
                                          "HoverWidget:hover:!pressed{background-color:rgb(255,255,255,15%);border-radius: 6px;}");
                nowAt = i-1;

                /*else if(i == 0){
                    qDebug()<<"enheng???111"<<list.count();
                    list.last()->setStyleSheet("HoverWidget{background-color:rgb(255,255,255,40%);border-radius: 6px;}"
                                              "HoverWidget:hover:!pressed{background-color:rgb(255,255,255,15%);border-radius: 6px;}");
                    nowAt = list.count() -1;
                }*/
            }
        }
    } else if(key == "Down") {
        for(int i = list.count(); i >= 0; i--){
            if(nowAt == i){
                if(i == list.count() - 1)
                    return ;
                list.at(i)->setStyleSheet("HoverWidget{background-color:transparent;}"
                                                      "HoverWidget:hover:!pressed{background-color:rgb(255,255,255,15%);border-radius: 6px;}");
                list.at(i+1)->setStyleSheet("HoverWidget{background-color:rgb(255,255,255,40%);border-radius: 6px;}"
                                          "HoverWidget:hover:!pressed{background-color:rgb(255,255,255,15%);border-radius: 6px;}");
                nowAt = i+1;
                /*else if(i == list.count() - 1){
                    qDebug()<<"enheng???111"<<list.count();
                    list.first()->setStyleSheet("HoverWidget{background-color:rgb(255,255,255,40%);border-radius: 6px;}"
                                              "HoverWidget:hover:!pressed{background-color:rgb(255,255,255,15%);border-radius: 6px;}");
                    nowAt = 0;
                }*/
            }
        }
    } else if(key == "Return" || key == "KP_Enter"){
        QModelIndex index = usersModel->index(nowAt, 0);
        Q_EMIT currentUserChanged(index);
        Q_EMIT userSelected(index);
        list.at(nowAt)->setStyleSheet("HoverWidget{background-color:rgb(255,255,255,40%);border-radius: 6px;}"
                                  "HoverWidget:hover:!pressed{background-color:rgb(255,255,255,15%);border-radius: 6px;}");
    }
}

