/*
 * Copyright (C) 2014-2022 CZ.NIC
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * In addition, as a special exception, the copyright holders give
 * permission to link the code of portions of this program with the
 * OpenSSL library under certain conditions as described in each
 * individual source file, and distribute linked combinations including
 * the two.
 */

#include <cmath> /* ::std::floor */
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonParseError>

#include "src/datovka_shared/json/helper.h"
#include "src/datovka_shared/log/log.h"

#ifdef Q_COMPILER_RVALUE_REFS
#  define macroStdMove(x) ::std::move(x)
#else /* Q_COMPILER_RVALUE_REFS */
#  define macroStdMove(x) (x)
#endif /* Q_COMPILER_RVALUE_REFS */

bool Json::Helper::readRootObject(const QByteArray &json, QJsonObject &jsonObj)
{
	QJsonDocument jsonDoc;
	{
		QJsonParseError parseErr;
		jsonDoc = QJsonDocument::fromJson(json, &parseErr);
		if (Q_UNLIKELY(jsonDoc.isNull())) {
			logErrorNL("Error parsing JSON: %s",
			    parseErr.errorString().toUtf8().constData());
			return false;
		}
	}
	if (Q_UNLIKELY(!jsonDoc.isObject())) {
		logErrorNL("%s", "JSON document contains no object.");
		return false;
	}

	QJsonObject jsonTmpObj(jsonDoc.object());
	if (Q_UNLIKELY(jsonTmpObj.isEmpty())) {
		logErrorNL("%s", "JSON object is empty.");
		return false;
	}

	jsonObj = macroStdMove(jsonTmpObj);
	return true;
}

bool Json::Helper::readRootArray(const QByteArray &json, QJsonArray &jsonArr)
{
	QJsonDocument jsonDoc;
	{
		QJsonParseError parseErr;
		jsonDoc = QJsonDocument::fromJson(json, &parseErr);
		if (Q_UNLIKELY(jsonDoc.isNull())) {
			logErrorNL("Error parsing JSON: %s",
			    parseErr.errorString().toUtf8().constData());
			return false;
		}
	}
	if (Q_UNLIKELY(!jsonDoc.isArray())) {
		logErrorNL("%s", "JSON document contains no array.");
		return false;
	}

	QJsonArray jsonTmpArr(jsonDoc.array());
	if (Q_UNLIKELY(jsonTmpArr.isEmpty())) {
		logWarningNL("%s", "JSON array is empty.");
		/* Allow empty arrays. */
		/* return false; */
	}

	jsonArr = macroStdMove(jsonTmpArr);
	return true;
}

/*!
 * @brief Searches for a value on JSON object.
 *
 * @param[in]  jsonObject Object to search in.
 * @param[in]  key Key to search for.
 * @param[out] jsonVal Found value.
 * @param[in]  noLogMissingKey True to disable logging of missing key errors.
 * @return True if key found, false else.
 */
static
bool _readValue(const QJsonObject &jsonObj, const QString &key,
    QJsonValue &jsonVal, bool noLogMissingKey)
{
	if (Q_UNLIKELY(jsonObj.isEmpty() || key.isEmpty())) {
		logErrorNL("%s", "JSON object or sought key is empty.");
		return false;
	}

	jsonVal = jsonObj.value(key);
	if (Q_UNLIKELY(jsonVal.isUndefined())) {
		if (!noLogMissingKey) {
			logErrorNL("Missing key '%s' in JSON object.",
			    key.toUtf8().constData());
		}
		return false;
	}

	return true;
}

bool Json::Helper::readValue(const QJsonObject &jsonObj, const QString &key,
    QJsonValue &val, int flags, const QJsonValue &defVal)
{
	QJsonValue jsonVal;
	if (!_readValue(jsonObj, key, jsonVal, (flags & ACCEPT_MISSING))) {
		val = defVal;
		return flags & ACCEPT_MISSING;
	}
	if (jsonVal.isNull()) {
		val = defVal;
		return flags & ACCEPT_NULL;
	}
	/*
	 * Cannot be invalid as it is already parsed and is a type of JSON
	 * value.
	 */

	val = macroStdMove(jsonVal);
	return true;
}

bool Json::Helper::valToBool(const QJsonValue &jsonVal, bool &val,
    PresenceFlags flags, bool defVal)
{
	if (jsonVal.isNull()) {
		val = defVal;
		return flags & ACCEPT_NULL;
	}
	if (Q_UNLIKELY(!jsonVal.isBool())) {
		logErrorNL("%s", "JSON value is not a boolean value.");
		val = defVal;
		return flags & ACCEPT_INVALID;
	}

	val = jsonVal.toBool();
	return true;
}

bool Json::Helper::readBool(const QJsonObject &jsonObj, const QString &key,
    bool &val, PresenceFlags flags, bool defVal)
{
	QJsonValue jsonVal;
	if (!_readValue(jsonObj, key, jsonVal, (flags & ACCEPT_MISSING))) {
		val = defVal;
		return flags & ACCEPT_MISSING;
	}
	if (jsonVal.isNull()) {
		val = defVal;
		return flags & ACCEPT_NULL;
	}
	if (Q_UNLIKELY(!jsonVal.isBool())) {
		logErrorNL("Value related to key '%s' is not a boolean value.",
		    key.toUtf8().constData());
		val = defVal;
		return flags & ACCEPT_INVALID;
	}

	val = jsonVal.toBool();
	return true;
}

bool Json::Helper::valToNilBool(const QJsonValue &jsonVal,
    enum Isds::Type::NilBool &val, PresenceFlags flags,
    enum Isds::Type::NilBool defVal)
{
	if (jsonVal.isNull()) {
		val = defVal;
		return flags & ACCEPT_NULL;
	}
	if (Q_UNLIKELY(!jsonVal.isBool())) {
		logErrorNL("%s", "JSON value is not a boolean value.");
		val = defVal;
		return flags & ACCEPT_INVALID;
	}

	val = jsonVal.toBool() ? Isds::Type::BOOL_TRUE : Isds::Type::BOOL_FALSE;
	return true;
}

bool Json::Helper::readNilBool(const QJsonObject &jsonObj, const QString &key,
    enum Isds::Type::NilBool &val, PresenceFlags flags,
    enum Isds::Type::NilBool defVal)
{
	QJsonValue jsonVal;
	if (!_readValue(jsonObj, key, jsonVal, (flags & ACCEPT_MISSING))) {
		val = defVal;
		return flags & ACCEPT_MISSING;
	}
	if (jsonVal.isNull()) {
		val = defVal;
		return flags & ACCEPT_NULL;
	}
	if (Q_UNLIKELY(!jsonVal.isBool())) {
		logErrorNL("Value related to key '%s' is not a boolean value.",
		    key.toUtf8().constData());
		val = defVal;
		return flags & ACCEPT_INVALID;
	}

	val = jsonVal.toBool() ? Isds::Type::BOOL_TRUE : Isds::Type::BOOL_FALSE;
	return true;
}

bool Json::Helper::valToInt(const QJsonValue &jsonVal, int &val,
    PresenceFlags flags, int defVal)
{
	if (jsonVal.isNull()) {
		val = defVal;
		return flags & ACCEPT_NULL;
	}
	bool isInt = false;
	int readVal = defVal;
	if (jsonVal.isDouble()) {
		readVal = jsonVal.toInt();
		double doubleVal = jsonVal.toDouble();
		isInt = (doubleVal == ::std::floor(doubleVal)) &&
		        (readVal == doubleVal);
	}
	if (Q_UNLIKELY(!isInt)) {
		logErrorNL("%s", "JSON value is not an integer value.");
		val = defVal;
		return flags & ACCEPT_INVALID;
	}

	val = readVal;
	return true;
}

bool Json::Helper::readInt(const QJsonObject &jsonObj, const QString &key,
    int &val, PresenceFlags flags, int defVal)
{
	QJsonValue jsonVal;
	if (!_readValue(jsonObj, key, jsonVal, (flags & ACCEPT_MISSING))) {
		val = defVal;
		return flags & ACCEPT_MISSING;
	}
	if (jsonVal.isNull()) {
		val = defVal;
		return flags & ACCEPT_NULL;
	}
	bool isInt = false;
	int readVal = defVal;
	if (jsonVal.isDouble()) {
		readVal = jsonVal.toInt();
		double doubleVal = jsonVal.toDouble();
		isInt = (doubleVal == ::std::floor(doubleVal)) &&
		        (readVal == doubleVal);
	}
	if (Q_UNLIKELY(!isInt)) {
		logErrorNL("Value related to key '%s' is not an integer.",
		    key.toUtf8().constData());
		val = defVal;
		return flags & ACCEPT_INVALID;
	}

	val = readVal;
	return true;
}

bool Json::Helper::valToQint64String(const QJsonValue &jsonVal, qint64 &val,
    PresenceFlags flags, qint64 defVal)
{
	QString valStr;
	if (!valToString(jsonVal, valStr, flags, QString())) {
		return false;
	}

	if (valStr.isEmpty() && flags) {
		val = defVal;
		return flags;
	}
	bool iOk = false;
	qint64 readVal = valStr.toLongLong(&iOk);
	if (Q_UNLIKELY(!iOk)) {
		logErrorNL("%s",
		    "JSON value is not a string containing an integer.");
		val = defVal;
		return flags & ACCEPT_INVALID;
	}

	val = readVal;
	return true;
}

bool Json::Helper::readQint64String(const QJsonObject &jsonObj,
    const QString &key, qint64 &val, PresenceFlags flags, qint64 defVal)
{
	QString valStr;
	if (!readString(jsonObj, key, valStr, flags, QString())) {
		return false;
	}

	if (valStr.isEmpty() && flags) {
		val = defVal;
		return flags;
	}
	bool iOk = false;
	qint64 readVal = valStr.toLongLong(&iOk);
	if (Q_UNLIKELY(!iOk)) {
		logErrorNL(
		    "Value related to key '%s' is not a string containing an integer.",
		    key.toUtf8().constData());
		val = defVal;
		return flags & ACCEPT_INVALID;
	}

	val = readVal;
	return true;
}

bool Json::Helper::readBase64DataString(const QJsonObject &jsonObj,
    const QString &key, QByteArray &val, PresenceFlags flags,
    const QByteArray &defVal)
{
	QString valStr;
	if (!readString(jsonObj, key, valStr, flags, QString())) {
		return false;
	}

	if (valStr.isEmpty() && flags) {
		val = defVal;
		return flags;
	}

#if (QT_VERSION >= QT_VERSION_CHECK(5, 15, 0))
	/* QByteArray::AbortOnBase64DecodingErrors has been added in Qt-5.15. */
	QByteArray readVal = QByteArray::fromBase64(valStr.toUtf8(),
	    QByteArray::AbortOnBase64DecodingErrors);
#else /* < Qt-5.15.0 */
	QByteArray readVal = QByteArray::fromBase64(valStr.toUtf8());
#endif /* >= Qt-5.15.0 */
	if (Q_UNLIKELY(readVal.isEmpty())) {
		logErrorNL("Value related to key '%s' is not a Base64 string.",
		    key.toUtf8().constData());
		val = defVal;
		return flags & ACCEPT_INVALID;
	}

	val = macroStdMove(readVal);
	return true;
}

bool Json::Helper::valToString(const QJsonValue &jsonVal, QString &val,
    PresenceFlags flags, const QString &defVal)
{
	if (jsonVal.isNull()) {
		val = defVal;
		return flags & ACCEPT_NULL;
	}
	if (Q_UNLIKELY(!jsonVal.isString())) {
		logErrorNL("%s", "JSON value is not a string.");
		val = defVal;
		return flags & ACCEPT_INVALID;
	}

	val = jsonVal.toString();
	return true;
}

bool Json::Helper::readString(const QJsonObject &jsonObj, const QString &key,
    QString &val, PresenceFlags flags, const QString &defVal)
{
	QJsonValue jsonVal;
	if (!_readValue(jsonObj, key, jsonVal, (flags & ACCEPT_MISSING))) {
		val = defVal;
		return flags & ACCEPT_MISSING;
	}
	if (jsonVal.isNull()) {
		val = defVal;
		return flags & ACCEPT_NULL;
	}
	if (Q_UNLIKELY(!jsonVal.isString())) {
		logErrorNL("Value related to key '%s' is not a string.",
		    key.toUtf8().constData());
		val = defVal;
		return flags & ACCEPT_INVALID;
	}

	val = jsonVal.toString();
	return true;
}

bool Json::Helper::readArray(const QJsonObject &jsonObj, const QString &key,
    QJsonArray &arr, PresenceFlags flags, const QJsonArray &defVal)
{
	QJsonValue jsonVal;
	if (!_readValue(jsonObj, key, jsonVal, (flags & ACCEPT_MISSING))) {
		arr = defVal;
		return flags & ACCEPT_MISSING;
	}
	if (jsonVal.isNull()) {
		arr = defVal;
		return flags & ACCEPT_NULL;
	}
	if (Q_UNLIKELY(!jsonVal.isArray())) {
		logErrorNL("Value related to key '%s' is not an array.",
		    key.toUtf8().constData());
		arr = defVal;
		return flags & ACCEPT_INVALID;
	}

	arr = jsonVal.toArray();
	return true;
}

bool Json::Helper::readStringList(const QJsonObject &jsonObj,
    const QString &key, QStringList &val, PresenceFlags flags,
    const QStringList &defVal)
{
	QJsonArray jsonArr;
	if (!readArray(jsonObj, key, jsonArr, flags)) {
		/* Missing, empty and invalid types result in empty list. */
		val = defVal;
		return false;
	}

	QStringList tmpList;

	for (const QJsonValue &jsonVal : jsonArr) {
		if (Q_UNLIKELY(jsonVal.isNull())) {
			logErrorNL("%s", "Found null value in array.");
			val = defVal;
			return false;
		}
		if (Q_UNLIKELY(!jsonVal.isString())) {
			logErrorNL("%s", "Found non-string value in array.");
			val = defVal;
			return false;
		}

		tmpList.append(jsonVal.toString());
	}

	val = macroStdMove(tmpList);
	return true;
}

bool Json::Helper::readQDateTimeString(const QJsonObject &jsonObj,
    const QString &key, QDateTime &val, PresenceFlags flags,
    const QDateTime &defVal)
{
	QString valStr;
	if (!readString(jsonObj, key, valStr, flags, QString())) {
		return false;
	}

	if (valStr.isEmpty() && flags) {
		val = defVal;
		return flags;
	}

	QDateTime readVal = QDateTime::fromString(valStr, Qt::ISODate);
	if (!readVal.isValid()) {
		val = defVal;
		return flags & ACCEPT_INVALID;
	}

	val = macroStdMove(readVal);
	return true;
}

QByteArray Json::Helper::toJsonData(const QJsonValue &jsonVal, bool indent)
{
	enum QJsonDocument::JsonFormat format =
	    indent ? QJsonDocument::Indented : QJsonDocument::Compact;

	if (jsonVal.isObject()) {
		return QJsonDocument(jsonVal.toObject()).toJson(format);
	} else if (jsonVal.isArray()) {
		return QJsonDocument(jsonVal.toArray()).toJson(format);
	} else {
		logErrorNL("%s",
		    "Cannot write non-object or non-array JSON value as a JSON document.");
		return QByteArray();
	}
}

QByteArray Json::Helper::reindent(const QByteArray &json, bool indent, bool *ok)
{
	if (json.isEmpty()) {
		if (ok != Q_NULLPTR) {
			*ok = false;
		}
		return QByteArray();
	}

	QJsonDocument jsonDoc;
	{
		QJsonParseError parseErr;
		jsonDoc = QJsonDocument::fromJson(json, &parseErr);
		if (Q_UNLIKELY(jsonDoc.isNull())) {
			logErrorNL("Error parsing JSON: %s",
			    parseErr.errorString().toUtf8().constData());
			if (ok != Q_NULLPTR) {
				*ok = false;
			}
			return QByteArray();
		}
	}

	if (ok != Q_NULLPTR) {
		*ok = true;
	}
	return jsonDoc.toJson(
	    indent ? QJsonDocument::Indented : QJsonDocument::Compact);
}
