/*****************************************************************************
 * $CAMITK_LICENCE_BEGIN$
 *
 * CamiTK - Computer Assisted Medical Intervention ToolKit
 * (c) 2001-2025 Univ. Grenoble Alpes, CNRS, Grenoble INP - UGA, TIMC, 38000 Grenoble, France
 *
 * Visit http://camitk.imag.fr for more information
 *
 * This file is part of CamiTK.
 *
 * CamiTK is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * CamiTK is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with CamiTK.  If not, see <http://www.gnu.org/licenses/>.
 *
 * $CAMITK_LICENCE_END$
 ****************************************************************************/

#include <QJsonDocument>

/// Utility class
///
/// useful for simplifying test code
///
class JsonUtils {
public:
    static void printJSON(QJsonObject data, bool indented = true) {
        qDebug().noquote().nospace() << QJsonDocument(data).toJson((indented) ? QJsonDocument::Indented : QJsonDocument::Compact);
    }

    /// @brief Creates a QJsonObject from a string
    ///
    /// e.g. JsonUtils::stringToJSON(R"json({ "field1": { "field2": 0} })json"));
    ///
    /// @param dataString the input string
    /// @param print if true prints the resulting a formatted json to stdout
    /// @return the build json object
    static QJsonObject stringToJSON(QString dataString, bool print = false) {
        QJsonParseError jsonParseError;
        QJsonDocument jsonDoc = QJsonDocument::fromJson(dataString.toUtf8(), &jsonParseError);
        if (jsonDoc.isNull()) {
            // extract the string from the error offset to the next return carriage
            QString jsonErrorData(dataString.mid(jsonParseError.offset, dataString.indexOf("\n", jsonParseError.offset) - jsonParseError.offset));
            int lineNr = dataString.left(jsonParseError.offset).count('\n');
            if (lineNr == 0) {
                qWarning().noquote().nospace() << "Error creating JSON from string \"" << dataString << "\":\n" << jsonParseError.errorString() << ":\n" << jsonErrorData << "\n" << "Please check that the input string is a valid JSON string";
            }
            else {
                QString errorLine(dataString.split('\n')[lineNr - 1]);
                qWarning().noquote().nospace() << "Error creating JSON from string \"" << dataString << "\":\n" << jsonParseError.errorString() << ":\n" << jsonErrorData << "\nOn line " << lineNr << ":\n" << errorLine;
            }
            return QJsonObject();
        }
        else if (!jsonDoc.isObject()) {
            qWarning().noquote().nospace() << "Error creating JSON from string \"" << dataString << "\":\n: JSON document is not an object";
            return QJsonObject();
        }
        else {
            QJsonObject data = jsonDoc.object();
            if (print) {
                printJSON(data);
            }
            return data;
        }
    }
};