#include "devicepanel.h"
#include "globaldefine.h"
#include "gutil/qgui.h"
#include "gutil/qnetwork.h"
#include "base/waitingdlg.h"
#include "deviceitem.h"
#include <QAction>
#include <QBoxLayout>
#include <QEvent>
#include <QHeaderView>
#include <QLineEdit>
#include <QNetworkDatagram>
#include <QNetworkInterface>
#include <QMessageBox>
#include <QJsonArray>
#include <QJsonObject>
#include <QStyledItemDelegate>

DevicePanel *gDevicePanel;
void setCard(LedCard &card, const QString &addr, const QJsonDocument &json) {
    if(! addr.isEmpty()) card.ip = addr;
    else {
        card.ip = json["newIp"].toString();
        if(card.ip.isEmpty()) card.ip = json["ip"].toString();
    }
    card.mWidth = json["width"].toInt();
    card.mHeight = json["height"].toInt();
    card.androidVersion = json["androidVersion"].toString();
}
DevicePanel::DevicePanel(QSettings &settings, QWidget *parent) : QWidget(parent) {
    gDevicePanel = this;
    setAutoFillBackground(true);
    QPalette pal;
    pal.setBrush(QPalette::Window, QColor(0xeeeeee));
    setPalette(pal);

    auto vBox = new VBox(this);
    vBox->setContentsMargins(0, 0, 0, 0);
    vBox->setSpacing(0);

    auto hBox = new HBox(vBox);
    hBox->setContentsMargins(6, 2, 6, 2);
    hBox->setSpacing(2);

    auto label = new QLabel();
    label->setPixmap({":/res/device/DeviceNum_All.png"});
    label->setScaledContents(true);
    label->setFixedSize(33, 24);
    hBox->addWidget(label);

    label_3 = new QLabel(tr("All"));
    hBox->addWidget(label_3);

    nDeviceNum = new QLabel();
    nDeviceNum->setFixedSize(40, 20);
    hBox->addWidget(nDeviceNum);

    auto fdSearch = new QLineEdit();
    fdSearch->setClearButtonEnabled(true);
    fdSearch->setFixedSize(220, 30);
    fdSearch->addAction(new QAction(QIcon(":/res/program/bnSearch.png"), QString()), QLineEdit::LeadingPosition);
    fdSearch->setStyleSheet("border: 1px solid #aaaaaa;");
    connect(fdSearch, &QLineEdit::textChanged, this, [this](const QString &search) {
        auto cnt = mDeviceTable->topLevelItemCount();
        if(search.isEmpty()) for(int i=0; i<cnt; i++) mDeviceTable->topLevelItem(i)->setHidden(false);
        else for(int i=0; i<cnt; i++) {
            auto item = mDeviceTable->topLevelItem(i);
            item->setHidden(! (item->text(DeviceTable_ID).contains(search) || item->text(DeviceTable_Remark).contains(search) || item->text(DeviceTable_IP).contains(search)));
        }
    });
    hBox->addWidget(fdSearch);

    hBox->addSpacing(10);

    fdCardNumInfo = new QLabel(tr("Current Screen")+": "+tr("none"));
    fdCardNumInfo->setStyleSheet("QLabel{color: #15f;}");
    fdCardNumInfo->hide();
    hBox->addWidget(fdCardNumInfo);

    hBox->addStretch();

    auto areaFlash = new QWidget();
    areaFlash->setFixedSize(100, 34);

    bnSpecifyIP = new QComboBox(areaFlash);
    bnSpecifyIP->addItem(tr("Specify IP"));
    bnSpecifyIP->setGeometry(0, 0, areaFlash->width(), areaFlash->height());
    bnSpecifyIP->setItemDelegate(new QStyledItemDelegate);
    connect(bnSpecifyIP, &QComboBox::textActivated, this, [this] {
        mUdpTimer.stop();
        specifyIPDlg->exec();
        mUdpTimer.start(30000);
 });
    bnSpecifyIP->setStyleSheet(R"rrr(
QComboBox {
    border: none;
    border-radius: 5px;
    background-color: #19c;
}
QComboBox:hover {background-color: #08b;}
QComboBox::drop-down {width: 25px;}
QComboBox::down-arrow {image: url(:/res/device/FlashArrow.png);}
QComboBox QAbstractItemView::item {
    height: 28px;
    color: #fff;
}
QComboBox QAbstractItemView::item:selected {background-color: #09c;}
)rrr");

    btnRefresh = new QPushButton(tr("Refresh"), areaFlash);
    btnRefresh->setGeometry(0, 0, 75, areaFlash->height());
    connect(btnRefresh, &QPushButton::clicked, this, [this] {
        mDeviceTable->onCheckAll(false);
        mDeviceTable->clear();
        nDeviceNum->setText("0");
        sendGetInfo();
    });
    btnRefresh->setStyleSheet(R"rrr(
QPushButton {
    border-radius: 5px;
    background-color: #19c;
    color: #fff;
}
QPushButton:hover {background-color: #08b;}
)rrr");

    hBox->addWidget(areaFlash);

    mHBox = new QHBoxLayout();

    mDeviceTable = new LoQTreeWidget(this);
    mDeviceTable->setSelectionMode(QAbstractItemView::NoSelection);
    mDeviceTable->setIndentation(0);
    mDeviceTable->setSortingEnabled(true);
    mHBox->addWidget(mDeviceTable);

    vBox->addLayout(mHBox);

    connect(&mUdpTimer, &QTimer::timeout, this, &DevicePanel::sendGetInfo);
    connect(&mUdpSocket, &QUdpSocket::readyRead, this, [this] {
        while(mUdpSocket.hasPendingDatagrams()) {
            auto gram = mUdpSocket.receiveDatagram();
            auto data = gram.data();
            if(data.isEmpty()) continue;
            auto senderAddress = gram.senderAddress();
            bool ok = true;
            if(senderAddress.protocol()==QUdpSocket::IPv6Protocol) senderAddress.setAddress(senderAddress.toIPv4Address(&ok));
            auto addr = ok ? senderAddress.toString() : "";
            DeviceItem *item;
            if(data.startsWith("{\"")) {
                QJsonParseError error;
                QJsonDocument json = QJsonDocument::fromJson(gram.data(), &error);
                if(error.error != QJsonParseError::NoError) {
                    qDebug()<<"DeviceItem OnProHttpResponse 解析json文件错误！";
                    continue;
                }
                auto cardId = json["cardId"].toString();
                int cnt = mDeviceTable->topLevelItemCount();
                for(int i=0; i<cnt; i++) if((item = (DeviceItem *)mDeviceTable->topLevelItem(i))->mCard.id==cardId) {
                    item->mCard.id = cardId;
                        item->mCard.isOnline = true;
                    setCard(item->mCard, addr, json);
                    item->init();
                    goto end;
                }
                item = new DeviceItem(mDeviceTable);
                item->mCard.id = cardId;
                setCard(item->mCard, addr, json);
            } else {
                auto bytes = gram.data();
                auto packet = (UDPPacket *)bytes.data();
                int cnt = mDeviceTable->topLevelItemCount();
                for(int i=0; i<cnt; i++) if((item = (DeviceItem *)mDeviceTable->topLevelItem(i))->mCard.id==packet->serialCode) {
                    item->mCard.id = packet->serialCode;
                    item->mCard.isOnline = true;
                    item->mCard.ip = addr;
                    item->init();
                    goto end;
                }
                item = new DeviceItem(mDeviceTable);
                item->mCard.id = packet->serialCode;
                item->mCard.ip = addr;
            }
            connect(item->m_bnCardDetailInfo, &QPushButton::clicked, item, [=] {
                QJsonObject json;
                json.insert("_id", "CheckSoftVersions");
                json.insert("_type", "CheckSoftVersions");
                auto waitingDlg = new WaitingDlg(this, tr("CheckSoftVersions")+" ...");
                waitingDlg->show();
                auto card = item->mCard;
                auto reply = NetReq("http://"+card.ip+":2016/settings").timeout(120000).post(json);
                waitingDlg->connAbort(reply);
                connect(reply, &QNetworkReply::finished, this, [=] {
                    Def_CtrlSingleGetReply
                    waitingDlg->close();
                    QString strTip;
                    strTip.append(tr("Current Brightness")).append(": ").append(QString::number(item->mCard.bright)).append("%").append("\n");
                    strTip.append(tr("Brightness Level")).append(": ").append(QString::number(item->mCard.BrightnessLevel)).append("\n");
                    strTip.append(tr("Android OS Resolution")).append(": ").append(item->mCard.ScreenResolution).append("\n");
                    strTip.append(tr("Android Version")).append(": ").append(item->mCard.androidVersion).append("\n");
                    strTip.append(tr("FPGA Version")).append(": ").append(item->mCard.HardVersion).append("\n");
                    strTip.append(tr("Firmware Version")).append(": ").append(item->mCard.FirmwareVersion).append("\n");
                    foreach(QJsonValue value, json["apps"].toArray()) {
                        QJsonObject app = value.toObject();
                        if(app["packageName"].toString().contains("xixunplayer")) strTip.append(tr("Player Version")).append(": ").append(app["versionName"].toString()).append("\n");
                    }
                    QMessageBox::information(this, tr("Detail Info"), strTip);
                });
            });
            item->init();
            item->DeviceItemHttpPost();
            nDeviceNum->setText(QString::number(mDeviceTable->topLevelItemCount()));
            {
                QJsonObject json;
                json.insert("_id", "SyncTime");
                json.insert("_type", "SyncTime");
                json.insert("time", QDateTime::currentDateTime().toMSecsSinceEpoch());
                auto reply = NetReq("http://"+item->mCard.ip+":2016/settings").timeout(60000).post(json);
                connect(reply, &QNetworkReply::finished, reply, &QNetworkReply::deleteLater);
            }
            end:;
        }
    });

    m_headerItem = new QTreeWidgetItem();
    for(int i=1; i<DeviceTable_End; i++) m_headerItem->setTextAlignment(i, Qt::AlignCenter);
    mDeviceTable->setHeaderItem(m_headerItem);
    mDeviceTable->header()->setSectionResizeMode(DeviceTable_Check, QHeaderView::Fixed);
    mDeviceTable->setColumnWidth(DeviceTable_Check, 36);
    mDeviceTable->header()->setSectionResizeMode(DeviceTable_Online, QHeaderView::Fixed);
    mDeviceTable->setColumnWidth(DeviceTable_Online, 48);
    mDeviceTable->header()->setSectionResizeMode(DeviceTable_ID, QHeaderView::Stretch);
    mDeviceTable->header()->setSectionResizeMode(DeviceTable_IP, QHeaderView::Stretch);
    mDeviceTable->header()->setSectionResizeMode(DeviceTable_ScreenSize, QHeaderView::Fixed);
    mDeviceTable->setColumnWidth(DeviceTable_ScreenSize, 108);
    mDeviceTable->header()->setSectionResizeMode(DeviceTable_Remark, QHeaderView::Stretch);
    mDeviceTable->header()->setSectionResizeMode(DeviceTable_Brightness, QHeaderView::Fixed);
    mDeviceTable->setColumnWidth(DeviceTable_Brightness, 108);
    mDeviceTable->header()->setSectionResizeMode(DeviceTable_Power, QHeaderView::Fixed);
    mDeviceTable->setColumnWidth(DeviceTable_Power, 84);
    mDeviceTable->header()->setSectionResizeMode(DeviceTable_Password, QHeaderView::Fixed);
    mDeviceTable->setColumnWidth(DeviceTable_Password, 72);
    mDeviceTable->header()->setSectionResizeMode(DeviceTable_Info, QHeaderView::Fixed);
    mDeviceTable->setColumnWidth(DeviceTable_Info, 72);
    mDeviceTable->header()->setSectionResizeMode(DeviceTable_Screenshot, QHeaderView::Fixed);
    mDeviceTable->setColumnWidth(DeviceTable_Screenshot, 72);

    connect(mDeviceTable, &LoQTreeWidget::sigCheckStateChanged, this, [=] {
        gSelCards.clear();
        int cnt = mDeviceTable->topLevelItemCount();
        for(int i=0; i<cnt; i++) if(mDeviceTable->topLevelItem(i)->checkState(0) == Qt::Checked) gSelCards.append(static_cast<DeviceItem*>(mDeviceTable->topLevelItem(i))->mCard);
        emit sigSelectedDeviceList();
    });
    mDeviceTable->hideColumn(0);
    mDeviceTable->fdIsSelAll->hide();

    specifyIPDlg = new QDialog(this);
    specifyIPDlg->setWindowTitle(tr("Specify IP"));

    vBox = new VBox(specifyIPDlg);
    vBox->addStretch();

    label = new QLabel(tr("Specify IP list"));
    label->setAlignment(Qt::AlignCenter);
    vBox->addWidget(label);

    fdIP = new QTextEdit;
    auto ipstr = settings.value("SpecifyIP").toString();
    if(! ipstr.isEmpty()) fdIP->setText(ipstr);
    fdIP->setPlaceholderText("192.168.1.1\n192.168.1.2\n  ...");
    fdIP->setMinimumWidth(160);
    vBox->addWidget(fdIP);

    hBox = new HBox(vBox);
    hBox->addStretch();

    auto bnSearch = new QPushButton(tr("Search"));
    connect(bnSearch, &QPushButton::clicked, this, [this] {
        QString ipsStr = fdIP->toPlainText();
        if(ipsStr.isEmpty()) {
            QMessageBox::warning(this, tr("Attention"), tr("Please input IP address!"));
            return;
        }
        auto ips = ipsStr.split("\n", Qt::SkipEmptyParts);
        if(ips.isEmpty()) {
            QMessageBox::warning(this, tr("Attention"), tr("Please input IP address!"));
            return;
        }
        QByteArray data = QJsonDocument(QJsonObject{{"action", "getInfo"}}).toJson(QJsonDocument::Compact);
        foreach(auto ip, ips) if(mUdpSocket.writeDatagram(data, QHostAddress(ip), 22222) != data.length()) qDebug() << "Specify IP write Failed." << ip;
        specifyIPDlg->accept();
    });
    hBox->addWidget(bnSearch);

    auto btnCancel = new QPushButton(tr("Cancel"));
    connect(btnCancel, &QPushButton::clicked, specifyIPDlg, &QDialog::reject);
    hBox->addWidget(btnCancel);
    hBox->addStretch();

    transUi();

    sendGetInfo();
    mUdpTimer.start(30000);
}

DevicePanel::~DevicePanel() {
    mUdpSocket.close();
    mUdpTimer.stop();
}

void DevicePanel::sendGetInfo() {
    const QByteArray data = QJsonDocument(QJsonObject{{"action", "getInfo"}}).toJson(QJsonDocument::Compact);
    uchar ccc[]{0x7E, 0x7E, 0x7E, 0x90, 0x42, 0x72, 0x6F, 0x61, 0x64, 0x63, 0x61, 0x73, 0x74, 0x21,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x1C, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x9F};
    if(mUdpSocket.writeDatagram(data, QHostAddress("255.255.255.255"), 22222) != data.length()) qDebug() << "getInfo write to 255.255.255.255 failed";
    if(mUdpSocket.writeDatagram((char *)ccc, sizeof(ccc), QHostAddress("255.255.255.255"), 31296) != sizeof(ccc)) qDebug() << "getInfo write to 255.255.255.255 failed";
    QList<QNetworkInterface> networkinterfaces = QNetworkInterface::allInterfaces();
    foreach(QNetworkInterface face, networkinterfaces) {
        auto flags = face.flags();
        bool can = (flags & QNetworkInterface::IsRunning) && (flags & QNetworkInterface::CanBroadcast) && ! (flags & QNetworkInterface::IsLoopBack);
        if(! can) continue;
        auto addrEntries = face.addressEntries();
        foreach(QNetworkAddressEntry addrEntry, addrEntries) {
            auto ip = addrEntry.ip();
            if(ip.protocol()!=QAbstractSocket::IPv4Protocol) continue;
            auto broadcast = addrEntry.broadcast();
            if(mUdpSocket.writeDatagram(data, broadcast, 22222) != data.length()) qDebug() << "getInfo write failed." << ip.toString() << "->" << broadcast.toString();
        }
    }
    auto ipstr = fdIP->toPlainText();
    if(! ipstr.isEmpty()) {
        auto ips = ipstr.split("\n", Qt::SkipEmptyParts);
        foreach(auto ip, ips) if(mUdpSocket.writeDatagram(data, QHostAddress(ip), 22222) != data.length()) qDebug() << "getInfo specify IP write failed." << ip;
    }
}

void DevicePanel::changeEvent(QEvent *event) {
    QWidget::changeEvent(event);
    if(event->type() == QEvent::LanguageChange) transUi();
}
void DevicePanel::transUi() {
    btnRefresh->setText(tr("Refresh"));
    bnSpecifyIP->setItemText(0,tr("Specify IP"));
    label_3->setText(tr("All"));

    m_headerItem->setText(DeviceTable_Online, tr("Online"));
    m_headerItem->setText(DeviceTable_ID, tr("Screen ID"));
    m_headerItem->setText(DeviceTable_IP, tr("Screen IP"));
    m_headerItem->setText(DeviceTable_ScreenSize, tr("Screen Size"));
    m_headerItem->setText(DeviceTable_Remark, tr("Remark Name"));
    m_headerItem->setText(DeviceTable_Screenshot, tr("readback pic"));
    m_headerItem->setText(DeviceTable_Brightness, tr("Cur Brightness"));
    m_headerItem->setText(DeviceTable_Power, tr("Power Status"));
    m_headerItem->setText(DeviceTable_Password, tr("Security"));
    m_headerItem->setText(DeviceTable_Info, tr("More Info"));

    auto cnt = mDeviceTable->topLevelItemCount();
    for(int i=0; i<cnt; i++) {
        auto item = (DeviceItem*) mDeviceTable->topLevelItem(i);
        item->setData(DeviceTable_Power, 0, item->mCard.isScreenOn ? tr("On") : tr("Off"));
    }
}
