#include "api/http/RestApiHttpConfig.h"

#include <QFile>
#include <QIODevice>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonParseError>

namespace softbus::api::http
{

bool loadRestApiHttpListenOptions(const QString& configPath, RestApiHttpListenOptions* out, QString* err)
{
    if (!out) {
        if (err) {
            *err = QStringLiteral("null_output");
        }
        return false;
    }
    *out = {};

    if (configPath.isEmpty()) {
        if (err) {
            *err = QStringLiteral("config_path_empty");
        }
        return false;
    }

    QFile f(configPath);
    if (!f.exists()) {
        return true;
    }
    if (!f.open(QIODevice::ReadOnly | QIODevice::Text)) {
        if (err) {
            *err = QStringLiteral("config_open_failed");
        }
        return false;
    }
    const QByteArray raw = f.readAll();
    f.close();

    QJsonParseError pe;
    const QJsonDocument doc = QJsonDocument::fromJson(raw, &pe);
    if (pe.error != QJsonParseError::NoError || !doc.isObject()) {
        if (err) {
            *err = QStringLiteral("config_json_invalid");
        }
        return false;
    }
    const QJsonObject root = doc.object();
    const QJsonObject api = root.value(QStringLiteral("api")).toObject();
    const QJsonObject httpCfg = api.value(QStringLiteral("http")).toObject();
    if (httpCfg.isEmpty()) {
        return true;
    }

    out->sectionPresent = true;
    out->enabled = httpCfg.value(QStringLiteral("enabled")).toBool(false);
    out->bindHost = httpCfg.value(QStringLiteral("bind")).toString(QStringLiteral("127.0.0.1"));
    if (out->bindHost.isEmpty()) {
        out->bindHost = QStringLiteral("127.0.0.1");
    }
    out->port = httpCfg.value(QStringLiteral("port")).toInt(18080);
    return true;
}

} // namespace softbus::api::http
