#include <QThread>

#include "device_information.h"
#include "network_device_monitor.h"
#include "network_device_detector.h"
#include "information_collector.h"

NetworkDeviceMonitor *NetworkDeviceMonitor::getInstance()
{
    static NetworkDeviceMonitor *instance = nullptr;
    static QThread *thread;
    if (nullptr == instance) {
        instance = new NetworkDeviceMonitor();
        thread = new QThread();
        instance->moveToThread(thread);
        instance->m_sendTestinfo = false;
        connect( instance,
                &NetworkDeviceMonitor::start,
                 instance,
                &NetworkDeviceMonitor::detectStart);
        
        connect(instance, &NetworkDeviceMonitor::getDeviceFromIP_async, instance, [=](const QString &ip, const int port, ProtocolType protocolType) {
            QList<DeviceInformation> devInfoList = instance->getDeviceFromIP(ip, port, protocolType);
            for (auto devInfo : devInfoList) {
                emit instance->getDeviceFromIP_cb(devInfo);
            }
        });
        thread->start();
    }
    return instance;
}

NetworkDeviceMonitor::NetworkDeviceMonitor()
{

}

NetworkDeviceMonitor::~NetworkDeviceMonitor()
{

}

void NetworkDeviceMonitor::detectStart()
{
    qDebug () <<"NetworkDeviceMonitor start!";
    if (this->m_sendTestinfo == true){
        DeviceInformation test;
        test.host = "192.168.17.90";
        test.connectType = ConnectType::InfoFrom_NETWORK_DETECT;
        test.protocolType = ProtocolType::SOCKET;
        test.uri = "socket://192.168.17.90:9100";
        test.name = "PRINTERFORTEST";
        test.model = "Brother";
        test.vendor = "DCP-7195DW";
        test.makeAndModel = "Brother DCP-7195DW";
        test.uuid = "e3248000-80ce-11db-8000-3c2af4f3d95f";
        test.serial = "E78133F0N443169";
        emit this->findNetworkConnect(test);
    }
    emit NetworkDeviceDetector::getInstance()->autoDetectStart();
    return;
}

QList<DeviceInformation> NetworkDeviceMonitor::getDeviceFromIP(const QString &ip, const int port, ProtocolType protocolType)
{
    InformationCollector::getInstance().addMessage(QString("get device from %1:") + ip);
    QList<DeviceInformation> infoList = NetworkDeviceDetector::getDeviceInfoFromHost(ip, port, protocolType);
    for (auto info : infoList) {
        InformationCollector::getInstance().addMessage(devInfoPrint(info));
    }
    return infoList;
}

