#include "deviceitem.h"
#include "globaldefine.h"
#include "base/waitingdlg.h"
#include "gutil/qgui.h"
#include "gutil/qnetwork.h"
#include <QMessageBox>
#include <QPainter>
#include <QInputDialog>
#include <QJsonObject>

DeviceItem::DeviceItem(LoQTreeWidget *parent) : QObject(parent), QTreeWidgetItem(UserType), m_parent(parent) {
    setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled);
    setCheckState(0, Qt::Unchecked);
    m_parent->addTopLevelItem(this);

    m_bnCardDetailInfo = new QPushButton();
    m_bnCardDetailInfo->setToolTip(tr("GetScreenDetailInfo"));
    m_bnCardDetailInfo->setCursor(QCursor(Qt::PointingHandCursor));
    m_bnCardDetailInfo->setStyleSheet(R"rrr(
QPushButton {
    border-radius: 4px;
    image: url(:/res/device/bnDetail.png);
}
QPushButton:hover{background-color: #ccc;}
)rrr");
    m_parent->setItemWidget(this, DeviceTable_Info, m_bnCardDetailInfo);

    m_bnReadbackPic = new QPushButton();
    m_bnReadbackPic->setToolTip(tr("ReadbackPic"));
    m_bnReadbackPic->setCursor(QCursor(Qt::PointingHandCursor));
    m_bnReadbackPic->setStyleSheet(R"rrr(
QPushButton {
    border-radius: 4px;
    image: url(:/res/device/deviceReadbackPic.png);
}
QPushButton:hover{background-color: #ccc;}
)rrr");
    connect(m_bnReadbackPic, &QPushButton::clicked, this, [this] {
        QJsonObject json;
        json.insert("_id", "GetScreenshotFull");
        json.insert("_type", "GetScreenshotFull");
        auto waitingDlg = new WaitingDlg(treeWidget(), tr("GetScreenshotFull")+" ...");
        waitingDlg->show();
        auto reply = NetReq("http://"+mCard.ip+":2016/settings").timeout(120000).post(json);
        waitingDlg->connAbort(reply);
        connect(reply, &QNetworkReply::finished, this, [=] {
            waitingDlg->close();
            QJsonDocument json;
            QString err = checkReplyForJson(reply, &json);
            if(! err.isEmpty()) {
                QMessageBox::critical(treeWidget(), tr("Error"), err);
                return;
            }
            ImgDlg dlg(QByteArray::fromBase64(json["data"].toString().toLatin1()), treeWidget());
            dlg.exec();
        });
    });
    m_parent->setItemWidget(this, DeviceTable_Screenshot, m_bnReadbackPic);

    m_ImageOnline = new QLabel;
    m_ImageOnline->setPixmap(QPixmap(":/res/device/O_Online.png"));
    m_ImageOnline->setAlignment(Qt::AlignCenter);
    m_parent->setItemWidget(this, DeviceTable_Online, m_ImageOnline);

    btnUnlock = new QPushButton;
    btnUnlock->setMaximumHeight(40);
    connect(btnUnlock, &QPushButton::clicked, this, [this] {
        if(! mCard.isLocked) return;
        bool ok;
        auto pwd = QInputDialog::getText(treeWidget(), tr("Input password"), tr("Input password"), QLineEdit::Password, QString(), &ok);
        if(! ok) return;
        QJsonObject json;
        json.insert("_id", "VerifyPassword");
        json.insert("_type", "VerifyPassword");
        json.insert("pwd", pwd);
        auto waitingDlg = new WaitingDlg(treeWidget(), tr("VerifyPassword")+" ...");
        waitingDlg->show();
        auto reply = NetReq("http://"+mCard.ip+":2016/settings").timeout(60000).post(json);
        waitingDlg->connAbort(reply);
        connect(reply, &QNetworkReply::finished, this, [=] {
            QJsonDocument json;
            QString err = checkReplyForJson(reply, &json);
            if(! err.isEmpty()) {
                waitingDlg->close();
                QMessageBox::critical(treeWidget(), tr("Error"), err);
                return;
            }
            if(! json["result"].toBool()) {
                waitingDlg->close();
                QMessageBox::critical(treeWidget(), tr("Tip Info"), tr("password is wrong"));
                return;
            }
            waitingDlg->success();
            mCard.isLocked = false;
            btnUnlock->setIcon(QIcon(":/res/device/UnLock.png"));
        });
    });
    auto wgt = new QWidget;
    auto hBox = new HBox(wgt);
    hBox->setContentsMargins(0,0,0,0);
    hBox->addWidget(btnUnlock);
    m_parent->setItemWidget(this, DeviceTable_Password, wgt);

    for(int i=1; i<DeviceTable_Screenshot; i++) setTextAlignment(i, Qt::AlignCenter);
}

void DeviceItem::init() {
    setData(DeviceTable_ID, 0, mCard.id);
    setData(DeviceTable_IP, 0, mCard.ip);
    setData(DeviceTable_ScreenSize, 0, QString("%1 x %2").arg(mCard.mWidth).arg(mCard.mHeight));
    if(mCard.hasPassword) btnUnlock->setIcon(QIcon(mCard.isLocked ? ":/res/device/Lock.png" : ":/res/device/UnLock.png"));
    else btnUnlock->hide();
}
void DeviceItem::DeviceItemHttpPost() {
    QJsonObject json;
    json.insert("_id", "GetBuildInformation");
    json.insert("_type", "GetBuildInformation");
    auto reply = NetReq("http://"+mCard.ip+":2016/settings").timeout(120000).post(json);
    connect(reply, &QNetworkReply::finished, this, [=] {
        QJsonDocument json;
        QString err = checkReplyForJson(reply, &json);
        if(! err.isEmpty()) return;
        mCard.BrightnessLevel = json["BrightnessLevel"].toInt();
        mCard.FirmwareVersion = json["FirmwareVersion"].toString();
        mCard.HardVersion = json["HardVersion"].toString();
        mCard.ScreenResolution = json["ScreenResolution"].toString();
        auto androidVersion = json["AndroidVersion"].toString();
        if(! androidVersion.isEmpty()) mCard.androidVersion = androidVersion;
    });

    json = QJsonObject();
    json.insert("_id", "GetScreenSize");
    json.insert("_type", "GetScreenSize");
    reply = NetReq("http://"+mCard.ip+":2016/settings").timeout(120000).post(json);
    connect(reply, &QNetworkReply::finished, this, [=] {
        QJsonDocument json;
        QString err = checkReplyForJson(reply, &json);
        if(! err.isEmpty()) return;
        mCard.mWidth = json["width"].toInt();
        mCard.mHeight = json["height"].toInt();
        setData(DeviceTable_ScreenSize, 0, QString("%1 x %2").arg(mCard.mWidth).arg(mCard.mHeight));
    });

    json = QJsonObject();
    json.insert("_id", "GetBrightness");
    json.insert("_type", "GetBrightness");
    reply = NetReq("http://"+mCard.ip+":2016/settings").timeout(120000).post(json);
    connect(reply, &QNetworkReply::finished, this, [=] {
        QJsonDocument json;
        QString err = checkReplyForJson(reply, &json);
        if(! err.isEmpty()) return;
        mCard.bright = json["brightnessPercentage"].toInt(-1);
        if(mCard.bright==-1) mCard.bright = qRound(json["brightness"].toInt() * 100.0 / mCard.BrightnessLevel);
        setData(DeviceTable_Brightness, 0, QString::number(mCard.bright)+"%");
    });
    json = QJsonObject();
    json.insert("_id", "IsScreenOn");
    json.insert("_type", "IsScreenOn");
    reply = NetReq("http://"+mCard.ip+":2016/settings").timeout(120000).post(json);
    connect(reply, &QNetworkReply::finished, this, [=] {
        QJsonDocument json;
        QString err = checkReplyForJson(reply, &json);
        if(! err.isEmpty()) return;
        mCard.isScreenOn = json["on"].toBool();
        setForeground(DeviceTable_Power, mCard.isScreenOn ? Qt::green : Qt::red);
        setData(DeviceTable_Power, 0, mCard.isScreenOn ? tr("On") : tr("Off"));
    });
    json = QJsonObject();
    json.insert("_id", "GetCardAlias");
    json.insert("_type", "GetCardAlias");
    reply = NetReq("http://"+mCard.ip+":2016/settings").timeout(120000).post(json);
    connect(reply, &QNetworkReply::finished, this, [=] {
        QJsonDocument json;
        QString err = checkReplyForJson(reply, &json);
        if(! err.isEmpty()) return;
        mCard.alias = QString::fromUtf8(QByteArray::fromBase64(json["alias"].toString().toLatin1()));
        setData(DeviceTable_Remark, 0, mCard.alias);
    });

    json = QJsonObject();
    json.insert("_id", "HasControllerPassword");
    json.insert("_type", "HasControllerPassword");
    reply = NetReq("http://"+mCard.ip+":2016/settings").timeout(120000).post(json);
    connect(reply, &QNetworkReply::finished, this, [=] {
        QJsonDocument json;
        QString err = checkReplyForJson(reply, &json);
        if(! err.isEmpty()) return;
        mCard.hasPassword = json["result"].toBool();
        if(mCard.hasPassword) {//加过密
            btnUnlock->show();
            btnUnlock->setIcon(QIcon(mCard.isLocked ? ":/res/device/Lock.png" : ":/res/device/UnLock.png"));
        } else btnUnlock->hide();
    });
}
ImgDlg::ImgDlg(const QByteArray &data, QWidget *parent) : QDialog(parent) {
    setWindowFlag(Qt::WindowContextHelpButtonHint, 0);
    setWindowTitle(tr("Screenshot"));
    mImg.loadFromData(data);
    auto www = mImg.width();
    auto hhh = mImg.height();
    if(www <= 1600 && hhh <= 900) resize(www, hhh);
    else if(www > hhh) resize(900 * www / hhh, 900);
    else resize(1600, 1600 * hhh / www);
}
void ImgDlg::paintEvent(QPaintEvent *) {
    QPainter painter(this);
    painter.drawImage(rect(), mImg);
}
