/*
 * Copyright (C) 2014-2020 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 <QByteArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonParseError>
#include <QJsonValue>

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

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

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

	jsonObj = jsonTmpObj;
	return true;
}

bool Json::Helper::readValue(const QJsonObject &jsonObj, const QString &key,
    QJsonValue &jsonVal, bool noLogMissingKey)
{
	if (jsonObj.isEmpty() || key.isEmpty()) {
		logErrorNL("%s", "JSON object or sought key is empty.");
		return false;
	}

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

	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 (!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::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 (!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::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 (!iOk) {
		val = defVal;
		return flags & ACCEPT_INVALID;
	}

	val = readVal;
	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 (!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 (!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;

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

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

	val = 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 = readVal;
	return true;
}

QString Json::Helper::toIndentedString(const QByteArray &json)
{
	if (json.isEmpty()) {
		return QString();
	}

	QJsonDocument jsonDoc;
	{
		QJsonParseError parseErr;
		jsonDoc = QJsonDocument::fromJson(json, &parseErr);
		if (jsonDoc.isNull()) {
			logErrorNL("Error parsing JSON: %s",
			    parseErr.errorString().toUtf8().constData());
			return QString();
		}
	}

	return QString::fromUtf8(jsonDoc.toJson(QJsonDocument::Indented));
}
