#include "HttpServer.h"

HttpServer::HttpServer(QObject *parent) : QObject(parent)
{
    httpServer = new QTcpServer(this);
    httpServer->setMaxPendingConnections(1024);
    QObject::connect(httpServer, &QTcpServer::newConnection, this, &HttpServer::newConnection);
}

HttpServer::~HttpServer()
{

}

HttpServer &HttpServer::instance()
{
    static HttpServer obj;
    return obj;
}

void HttpServer::run(const QHostAddress &address, const quint16 &port)
{
    httpServer->listen(address, port);
}

void HttpServer::newConnection()
{
    QTcpSocket * m_socket = httpServer->nextPendingConnection();
    QObject::connect(m_socket, &QTcpSocket::readyRead, this, &HttpServer::readyRead);
}

void HttpServer::readyRead()
{
    QTcpSocket * socket = qobject_cast<QTcpSocket*>(sender());
    if(socket) {
        QByteArray request = socket->readAll();

        qDebug() << "Request Data:" << request;

        QByteArray response = this->buildHeartBeatResponse().toUtf8();

        QString http = "HTTP/1.1 200 OK\r\n";
        http += "Server: qt\r\n";
        http += "Content-Type: application/json;charset=utf-8\r\n";
        http += "Connection: keep-alive\r\n";
        http += QString("Content-Length: %1\r\n\r\n").arg(QString::number(response.size()));

        socket->write(http.toUtf8());
        socket->write(response);
        socket->flush();
        socket->waitForBytesWritten(http.size() + response.size());
        socket->close();
    }
}

QString HttpServer::buildHeartBeatResponse()
{
    QJsonObject resp;
    resp.insert("code", 200);
    resp.insert("success", true);

    QJsonObject data;
    data.insert("status", "1");
    data.insert("remarks", "");
    resp.insert("data", data);

    return QString(QJsonDocument(resp).toJson(QJsonDocument::Compact));
}
