//#pragma execution_character_set("utf-8")

#include "applive.h"
#include "qmutex.h"
#include "qudpsocket.h"
#include "qtcpsocket.h"
#include "qstringlist.h"
#include "qapplication.h"
#include "qdatetime.h"
#include "qdebug.h"
#include "QDebug"
#define TIMEMS qPrintable(QTime::currentTime().toString("HH:mm:ss zzz"))

QScopedPointer<AppLive> AppLive::self;
AppLive *AppLive::Instance()
{
    if (self.isNull()) {
        QMutex mutex;
        QMutexLocker locker(&mutex);
        if (self.isNull()) {
            self.reset(new AppLive);
        }
    }

    return self.data();
}

AppLive::AppLive(QObject *parent) : QObject(parent)
{
    qDebug() <<"$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$";
    qDebug() <<"$       Module: Livedemo";
    qDebug() <<"$         Date:" <<__DATE__;
    qDebug() <<"$         Time:" <<__TIME__;
    qDebug() <<"$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$";
    //udpServer  = new QUdpSocket(this);//QUdpSocket(this);

    tcpServer  = new QTcpSocket(this);//QUdpSocket(this);

    QString name = qApp->applicationFilePath();
    QStringList list = name.split("/");
    appName = list.at(list.count() - 1).split(".").at(0);
}
AppLive::~AppLive()
{
    ;
}

void AppLive::readData()
{
    QByteArray byteArrays =tcpServer->readAll();
    qDebug() <<"TcpServerLib::readyRead =" <<byteArrays;
    QList<QByteArray> byteArrayList =byteArrays.split('\n');

    foreach (QByteArray byteArray, byteArrayList) {
        if(byteArray.isEmpty())
            continue;
//        QJsonArray appIdJsonArray;
//        QJsonValue infos;
//        QString key;
//        SubAppTcpSocket::AppId fromId =SubAppTcpSocket::getInform(byteArray,
//                                                                        appIdJsonArray,
//                                                                        key, infos);
        QString data = QLatin1String(byteArray);
        
        qDebug() <<"RXD =" <<data;
        if (data == "Hello") {
            tcpServer->write(QByteArray("OK\r\n").append(qApp->applicationName()));//往守护进程发程序名
        }
//        qDebug() <<"key =" <<key;
//        qDebug() <<"appIdJsonArray =" <<appIdJsonArray;
//        qDebug() <<"infos =" <<infos;
//        foreach (ProcessObject* processObject, processObjectList) {
//            if(processObject->appId ==fromId) {
//                if(!processObject->tcpSocket) {
//                    processObject->tcpSocket =tcpSocket;
//                }
//                processObject->timeout =0;
//            }
//            else if(appIdJsonArray.contains((int)processObject->appId)
//                    &&processObject->tcpSocket) {
//                processObject->tcpSocket->write(byteArray.append('\n'));
//            }
//        }
    }
//    QByteArray tempData;

//    do {
//        tempData.resize(udpServer->pendingDatagramSize());
//        QHostAddress sender;
//        quint16 senderPort;
//        udpServer->readDatagram(tempData.data(), tempData.size(), &sender, &senderPort);
//        QString data = QLatin1String(tempData);

//        if (data == "hello") {
//            udpServer->writeDatagram(QString("%1OK").arg(appName).toLatin1(), sender, senderPort);
//        }
//    } while (udpServer->hasPendingDatagrams());
}

bool AppLive::start(int port)
{
//    bool ok = udpServer->bind(port);
//    if (ok) {
//        connect(udpServer, SIGNAL(readyRead()), this, SLOT(readData()));
//        qDebug() << TIMEMS << "Start AppLive Ok";
//    }
//    bool ok = tcpServer->bind(port);
//    if (ok) {
//        connect(tcpServer, SIGNAL(readyRead()), this, SLOT(readData()));
//        qDebug() << TIMEMS << "Start AppLive Ok";
//    }
    bool ok = true;//tcpServer->bind(44555);
    if (ok) {
        connect(tcpServer, SIGNAL(readyRead()), this, SLOT(readData()));
        tcpServer->connectToHost(QString("127.0.0.1"),port);
        qDebug() << TIMEMS << "Start AppLive Ok";
    }
    return ok;
}

void AppLive::stop()
{
//    udpServer->abort();
//    disconnect(udpServer, SIGNAL(readyRead()), this, SLOT(readData()));
    tcpServer->abort();
    disconnect(tcpServer, SIGNAL(readyRead()), this, SLOT(readData()));
}
