/*
 * Copyright (C) 2014-2024 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 <QJsonObject>
#include <QJsonValue>
#include <utility> /* ::std::swap */

#include "src/datovka_shared/compat/compiler.h" /* macroStdMove */
#include "src/datovka_shared/json/helper.h"
#include "src/datovka_shared/records_management/json/entry_error.h"

/* Null objects - for convenience. */
static const RecMgmt::ErrorEntry::Code nullCode = RecMgmt::ErrorEntry::ERR_NO_ERROR;
static const QString nullString;

static
const QString keyCode("code");
static
const QString keyDescription("description");

static const QString strNoError("NO_ERROR"); /* This one should not be used. */
static const QString strMalformedRequest("MALFORMED_REQUEST");
static const QString strMissingIdentifier("MISSING_IDENTIFIER");
static const QString strWrongIdentifier("WRONG_IDENTIFIER");
static const QString strUnsupportedFileFormat("UNSUPPORTED_FILE_FORMAT");
static const QString strAlreadyPresent("ALREADY_PRESENT");
static const QString strLimitExceeded("LIMIT_EXCEEDED");
static const QString strUnspecified("UNSPECIFIED");

class RecMgmt::ErrorEntryPrivate {
public:
	ErrorEntryPrivate(void)
	    : m_code(nullCode), m_description()
	{ }

	ErrorEntryPrivate &operator=(const ErrorEntryPrivate &other) Q_DECL_NOTHROW
	{
		m_code = other.m_code;
		m_description = other.m_description;

		return *this;
	}

	bool operator==(const ErrorEntryPrivate &other) const
	{
		return (m_code == other.m_code) &&
		    (m_description == other.m_description);
	}

	enum ErrorEntry::Code m_code; /*!< Error code. */
	QString m_description; /*!< Error description as obtained from JSON. */
};

RecMgmt::ErrorEntry::ErrorEntry(void)
    : Json::Object(),
    d_ptr(Q_NULLPTR)
{
}

RecMgmt::ErrorEntry::ErrorEntry(const ErrorEntry &other)
    : Json::Object(),
    d_ptr((other.d_func() != Q_NULLPTR) ? (new (::std::nothrow) ErrorEntryPrivate) : Q_NULLPTR)
{
	Q_D(ErrorEntry);
	if (d == Q_NULLPTR) {
		return;
	}

	*d = *other.d_func();
}

#ifdef Q_COMPILER_RVALUE_REFS
RecMgmt::ErrorEntry::ErrorEntry(ErrorEntry &&other) Q_DECL_NOEXCEPT
    : Json::Object(),
#if (QT_VERSION >= QT_VERSION_CHECK(5, 12, 0))
    d_ptr(other.d_ptr.release()) //d_ptr(::std::move(other.d_ptr))
#else /* < Qt-5.12 */
    d_ptr(other.d_ptr.take())
#endif /* >= Qt-5.12 */
{
}
#endif /* Q_COMPILER_RVALUE_REFS */

RecMgmt::ErrorEntry::~ErrorEntry(void)
{
}

RecMgmt::ErrorEntry::ErrorEntry(enum Code code, const QString &description)
    : Json::Object(),
    d_ptr(new (::std::nothrow) ErrorEntryPrivate)
{
	Q_D(ErrorEntry);
	d->m_code = code;
	d->m_description = description;
}

#ifdef Q_COMPILER_RVALUE_REFS
RecMgmt::ErrorEntry::ErrorEntry(enum Code code, QString &&description)
    : Json::Object(),
    d_ptr(new (::std::nothrow) ErrorEntryPrivate)
{
	Q_D(ErrorEntry);
	d->m_code = code;
	d->m_description = ::std::move(description);
}
#endif /* Q_COMPILER_RVALUE_REFS */

/*!
 * @brief Ensures ErrorEntryPrivate presence.
 *
 * @note Returns if ErrorEntryPrivate could not be allocated.
 */
#define ensureErrorEntryPrivate(_x_) \
	do { \
		if (Q_UNLIKELY(d_ptr == Q_NULLPTR)) { \
			ErrorEntryPrivate *p = new (::std::nothrow) ErrorEntryPrivate; \
			if (Q_UNLIKELY(p == Q_NULLPTR)) { \
				Q_ASSERT(0); \
				return _x_; \
			} \
			d_ptr.reset(p); \
		} \
	} while (0)

RecMgmt::ErrorEntry &RecMgmt::ErrorEntry::operator=(const ErrorEntry &other) Q_DECL_NOTHROW
{
	if (other.d_func() == Q_NULLPTR) {
		d_ptr.reset(Q_NULLPTR);
		return *this;
	}
	ensureErrorEntryPrivate(*this);
	Q_D(ErrorEntry);

	*d = *other.d_func();

	return *this;
}

#ifdef Q_COMPILER_RVALUE_REFS
RecMgmt::ErrorEntry &RecMgmt::ErrorEntry::operator=(ErrorEntry &&other) Q_DECL_NOTHROW
{
	swap(*this, other);
	return *this;
}
#endif /* Q_COMPILER_RVALUE_REFS */

bool RecMgmt::ErrorEntry::operator==(const ErrorEntry &other) const
{
	Q_D(const ErrorEntry);
	if ((d == Q_NULLPTR) && ((other.d_func() == Q_NULLPTR))) {
		return true;
	} else if ((d == Q_NULLPTR) || ((other.d_func() == Q_NULLPTR))) {
		return false;
	}

	return *d == *other.d_func();
}

bool RecMgmt::ErrorEntry::operator!=(const ErrorEntry &other) const
{
	return !operator==(other);
}

void RecMgmt::ErrorEntry::swap(ErrorEntry &first, ErrorEntry &second) Q_DECL_NOTHROW
{
	using ::std::swap;
	swap(first.d_ptr, second.d_ptr);
}

bool RecMgmt::ErrorEntry::isNull(void) const
{
	Q_D(const ErrorEntry);
	return d == Q_NULLPTR;
}

enum RecMgmt::ErrorEntry::Code RecMgmt::ErrorEntry::code(void) const
{
	Q_D(const ErrorEntry);
	if (Q_UNLIKELY(d == Q_NULLPTR)) {
		return nullCode;
	}

	return d->m_code;
}

void RecMgmt::ErrorEntry::setCode(enum Code c)
{
	ensureErrorEntryPrivate();
	Q_D(ErrorEntry);
	d->m_code = c;
}

const QString &RecMgmt::ErrorEntry::description(void) const
{
	Q_D(const ErrorEntry);
	if (Q_UNLIKELY(d == Q_NULLPTR)) {
		return nullString;
	}

	return d->m_description;
}

void RecMgmt::ErrorEntry::setDescription(const QString &de)
{
	ensureErrorEntryPrivate();
	Q_D(ErrorEntry);
	d->m_description = de;
}

#ifdef Q_COMPILER_RVALUE_REFS
void RecMgmt::ErrorEntry::setDescription(QString &&de)
{
	ensureErrorEntryPrivate();
	Q_D(ErrorEntry);
	d->m_description = ::std::move(de);
}
#endif /* Q_COMPILER_RVALUE_REFS */

RecMgmt::ErrorEntry RecMgmt::ErrorEntry::fromJsonVal(const QJsonValue &jsonVal,
    bool *ok)
{
	if (jsonVal.isNull()) {
		if (ok != Q_NULLPTR) {
			*ok = true;
		}
		return ErrorEntry();
	}

	ErrorEntry ee;
	QString valStr;

	if (Q_UNLIKELY(!jsonVal.isObject())) {
		goto fail;
	}

	{
		const QJsonObject jsonObj = jsonVal.toObject();

		if (Json::Helper::readString(jsonObj, keyCode, valStr,
		        Json::Helper::ACCEPT_VALID)) {
			bool iOk = false;
			ee.setCode(stringToCode(valStr, &iOk));
			if (Q_UNLIKELY(!iOk)) {
				goto fail;
			}
		} else {
			goto fail;
		}
		if (Json::Helper::readString(jsonObj, keyDescription, valStr,
		        Json::Helper::ACCEPT_VALID)) {
			ee.setDescription(macroStdMove(valStr));
		} else {
			goto fail;
		}

		if (ok != Q_NULLPTR) {
			*ok = true;
		}
		return ee;
	}

fail:
	if (ok != Q_NULLPTR) {
		*ok = false;
	}
	return ErrorEntry();
}

bool RecMgmt::ErrorEntry::toJsonVal(QJsonValue &jsonVal) const
{
	if (code() == ERR_NO_ERROR) {
		jsonVal = QJsonValue();
		return true;
	}

	QJsonObject jsonObj;

	jsonObj.insert(keyCode, codeToString(code()));
	jsonObj.insert(keyDescription, description());

	jsonVal = jsonObj;
	return true;
}

QString RecMgmt::ErrorEntry::trVerbose(void) const
{
	QString retStr(codeToString(code()) + QLatin1String(" ("));
	QString explanation;

	switch (code()) {
	case ERR_NO_ERROR:
		explanation = tr("No error occurred");
		break;
	case ERR_MALFORMED_REQUEST:
		explanation = tr("Request was malformed");
		break;
	case ERR_MISSING_IDENTIFIER:
		explanation = tr("Identifier is missing");
		break;
	case ERR_WRONG_IDENTIFIER:
		explanation = tr("Supplied identifier is wrong");
		break;
	case ERR_UNSUPPORTED_FILE_FORMAT:
		explanation = tr("File format is not supported");
		break;
	case ERR_ALREADY_PRESENT:
		explanation = tr("Data are already present");
		break;
	case ERR_LIMIT_EXCEEDED:
		explanation = tr("Service limit was exceeded");
		break;
	case ERR_UNSPECIFIED:
		explanation = tr("Unspecified error");
		break;
	default:
		Q_ASSERT(0);
		explanation = tr("Unknown error");
		break;
	}

	retStr += explanation + QLatin1String(")");
	return retStr;
}

const QString &RecMgmt::ErrorEntry::codeToString(enum Code code)
{
	switch (code) {
	case ERR_NO_ERROR:
		Q_ASSERT(0); /* This one should never occur. */
		return strNoError;
		break;
	case ERR_MALFORMED_REQUEST:
		return strMalformedRequest;
		break;
	case ERR_MISSING_IDENTIFIER:
		return strMissingIdentifier;
		break;
	case ERR_WRONG_IDENTIFIER:
		return strWrongIdentifier;
		break;
	case ERR_UNSUPPORTED_FILE_FORMAT:
		return strUnsupportedFileFormat;
		break;
	case ERR_ALREADY_PRESENT:
		return strAlreadyPresent;
		break;
	case ERR_LIMIT_EXCEEDED:
		return strLimitExceeded;
		break;
	case ERR_UNSPECIFIED:
		return strUnspecified;
		break;
	default:
		Q_ASSERT(0);
		return strUnspecified;
		break;
	}
}

enum RecMgmt::ErrorEntry::Code RecMgmt::ErrorEntry::stringToCode(
    const QString &str, bool *ok)
{
	if (str == strNoError) {
		if (ok != Q_NULLPTR) {
			*ok = true;
		}
		return ERR_NO_ERROR;
	} else if (str == strMalformedRequest) {
		if (ok != Q_NULLPTR) {
			*ok = true;
		}
		return ERR_MALFORMED_REQUEST;
	} else if (str == strMissingIdentifier) {
		if (ok != Q_NULLPTR) {
			*ok = true;
		}
		return ERR_MISSING_IDENTIFIER;
	} else if (str == strWrongIdentifier) {
		if (ok != Q_NULLPTR) {
			*ok = true;
		}
		return ERR_WRONG_IDENTIFIER;
	} else if (str == strUnsupportedFileFormat) {
		if (ok != Q_NULLPTR) {
			*ok = true;
		}
		return ERR_UNSUPPORTED_FILE_FORMAT;
	} else if (str == strAlreadyPresent) {
		if (ok != Q_NULLPTR) {
			*ok = true;
		}
		return ERR_ALREADY_PRESENT;
	} else if (str == strLimitExceeded) {
		if (ok != Q_NULLPTR) {
			*ok = true;
		}
		return ERR_LIMIT_EXCEEDED;
	} else if (str == strUnspecified) {
		if (ok != Q_NULLPTR) {
			*ok = true;
		}
		return ERR_UNSPECIFIED;
	} else {
		if (ok != Q_NULLPTR) {
			*ok = false;
		}
		return ERR_UNSPECIFIED;
	}
}
