#include "httpserver.h"
#include <QStringList>

HttpServerd::HttpServerd(QObject *parent)
    : QObject(parent),
      _server(new QTcpServer(this))
{
    connect(_server, SIGNAL(newConnection()), this, SLOT(onNewConnection()));
}

bool HttpServerd::listen(quint16 port)
{
    return _server->listen(QHostAddress::Any, port);
}

void HttpServerd::onNewConnection()
{
    while (_server->hasPendingConnections()) {
        QTcpSocket *clientConnection = _server->nextPendingConnection();
        connect(clientConnection, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
        connect(clientConnection, SIGNAL(disconnected()), clientConnection, SLOT(deleteLater()));
    }
}

void HttpServerd::set_data_thread(Mthread *provider) {
    _mthread = provider;
}

void HttpServerd::onReadyRead()
{
    QTcpSocket *client = qobject_cast<QTcpSocket*>(sender());
    if (!client)
        return;

    QByteArray request = client->readAll();
    QString requestStr = QString::fromUtf8(request);

    // Разбор первой строки запроса
    QStringList lines = requestStr.split("\r\n");
    if (lines.isEmpty()) {
        client->disconnectFromHost();
        return;
    }

    QString requestLine = lines.at(0);
    // Пример: "GET /api/v5/3 HTTP/1.1"
    QStringList parts = requestLine.split(" ");
    if (parts.size() < 3) {
        client->disconnectFromHost();
        return;
    }

    QString method = parts.at(0);
    QString path = parts.at(1);

    if (method != "GET") {
        // Отвечаем 405 Method Not Allowed если требуется
        QByteArray response;
        response += "HTTP/1.1 405 Method Not Allowed\r\n";
        response += "Content-Length: 0\r\n";
        response += "Connection: close\r\n\r\n";
        client->write(response);
        client->disconnectFromHost();
        return;
    }

    // Разбираем путь вида /api/v5/<num>
    QRegExp regex("^/api/v5/(\\d+)$");
    if (regex.indexIn(path) != -1) {
        QString number = regex.cap(1);
        QByteArray responseBody;
        bool ok = false;
        int ss = number.toInt(&ok);
        if (ok) {
            if(ss == 1) {
               ss =  _mthread->http_status();
               number = QString::number(ss);
            }

            if(ss == 2) {
                number = _mthread->http_getcard();
            }
            if(ss == 3) {
                ss = _mthread->http_reboot();
                number = QString::number(ss);
            }

            // Формируем ответ — например, возвращаем JSON
            responseBody = QString("{\"res\":%1}").arg(number).toUtf8();

            // Успешно преобразовали строку в int
        } else {
            // Формируем ответ — например, возвращаем JSON
            responseBody = QString("{\"err\":%1}").arg(number).toUtf8();

            // Не удалось преобразовать — обработайте ошибку
        }


        QByteArray response;
        response += "HTTP/1.1 200 OK\r\n";
        response += "Content-Type: application/json\r\n";
        response += QString("Content-Length: %1\r\n").arg(responseBody.size()).toUtf8();
        response += "Connection: close\r\n";
        response += "\r\n";
        response += responseBody;

        client->write(response);
        client->disconnectFromHost();
    }
    else {
        // Для всех остальных путей - 404 Not Found
        QByteArray response;
        QString responseBody = "404 Not Found";
        response += "HTTP/1.1 404 Not Found\r\n";
        response += "Content-Type: text/html\r\n";
        response += QString("Content-Length: %1\r\n").arg(responseBody.size()).toUtf8();
        response += "Connection: close\r\n";
        response += "\r\n";
        response += responseBody.toUtf8();

        client->write(response);
        client->disconnectFromHost();
    }
}

#ifndef HTTPSERVER_H
#define HTTPSERVER_H

#include "mthread.h"

#include <QObject>
#include <QTcpServer>
#include <QTcpSocket>


class Mthread;

class HttpServerd : public QObject
{
    Q_OBJECT

public:
    explicit HttpServerd(QObject *parent = 0);
    bool listen(quint16 port);
    void set_data_thread(Mthread *provider);

private slots:
    void onNewConnection();
    void onReadyRead();

private:
    QTcpServer *_server;
    Mthread *_mthread;

signals:
    void http_send(int);
};

#endif // HTTPSERVER_H

Главный тред
 //------------------------------------------

   if (!HTTP.listen(80)) {
       qWarning("Не удалось запустить сервер");

   }
   QObject::connect(&HTTP, SIGNAL(http_send(int)), this, SLOT(_send_http(int)));
   
   HTTP.set_data_thread(this);

   qDebug("Сервер запущен на порту 8080");