/*
 * 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 <QHash> /* ::qHash */
#include <QJsonObject>
#include <QString>
#include <utility> /* ::std::swap */

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

#define INVALID_TAG_ID -1
#define DFLT_COLOUR "ffffff"
static const QString nullString;

/*!
 * @brief PIMPL TagEntry class.
 */
class Json::TagEntryPrivate {
	//Q_DISABLE_COPY(TagEntryPrivate)
public:
	TagEntryPrivate(void)
	    : m_id(INVALID_TAG_ID), m_name(), m_colour(DFLT_COLOUR),
	    m_description()
	{ }

	TagEntryPrivate &operator=(const TagEntryPrivate &other) Q_DECL_NOTHROW
	{
		m_id = other.m_id;
		m_name = other.m_name;
		m_colour = other.m_colour;
		m_description = other.m_description;

		return *this;
	}

	bool operator==(const TagEntryPrivate &other) const
	{
		return (m_id == other.m_id) &&
		    (m_name == other.m_name) &&
		    (m_colour == other.m_colour) &&
		    (m_description == other.m_description);
	}

	qint64 m_id; /*!< Tag identifier. */
	QString m_name; /*!< Name of the tag. */
	QString m_colour; /*!<
	                   * Colour of the tag in hex format without
	                   * the leading hashtag.
	                   */
	QString m_description; /*!< Tag description. */
};

Json::TagEntry::TagEntry(void)
    : Object(),
    d_ptr(Q_NULLPTR)
{
}

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

	*d = *other.d_func();
}

#ifdef Q_COMPILER_RVALUE_REFS
Json::TagEntry::TagEntry(TagEntry &&other) Q_DECL_NOEXCEPT
    : 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 */

Json::TagEntry::~TagEntry(void)
{
}

Json::TagEntry::TagEntry(qint64 id, const QString &name,
    const QString &colour, const QString &description)
    : Object(),
    d_ptr(new (::std::nothrow) TagEntryPrivate)
{
	Q_D(TagEntry);
	d->m_id = id;
	d->m_name = name;
	d->m_colour = colour;
	d->m_description = description;
}

#ifdef Q_COMPILER_RVALUE_REFS
Json::TagEntry::TagEntry(qint64 id, QString &&name, QString &&colour,
    QString &&description)
    : Object(),
    d_ptr(new (::std::nothrow) TagEntryPrivate)
{
	Q_D(TagEntry);
	d->m_id = id;
	d->m_name = ::std::move(name);
	d->m_colour = ::std::move(colour);
	d->m_description = ::std::move(description);
}
#endif /* Q_COMPILER_RVALUE_REFS */

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

Json::TagEntry &Json::TagEntry::operator=(const TagEntry &other) Q_DECL_NOTHROW
{
	if (other.d_func() == Q_NULLPTR) {
		d_ptr.reset(Q_NULLPTR);
		return *this;
	}
	ensureTagEntryPrivate(*this);
	Q_D(TagEntry);

	*d = *other.d_func();

	return *this;
}

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

bool Json::TagEntry::operator==(const TagEntry &other) const
{
	Q_D(const TagEntry);
	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 Json::TagEntry::operator!=(const TagEntry &other) const
{
	return !operator==(other);
}

bool Json::TagEntry::isNull(void) const
{
	Q_D(const TagEntry);
	return d == Q_NULLPTR;
}

bool Json::TagEntry::isValid(void) const
{
	/* TODO -- Use Colour::isValidColourStr(). */
	return !isNull() && (id() >= 0) && !name().isEmpty() && (6 == colour().size());
}

qint64 Json::TagEntry::id(void) const
{
	Q_D(const TagEntry);
	if (Q_UNLIKELY(d == Q_NULLPTR)) {
		return INVALID_TAG_ID;
	}

	return d->m_id;
}

void Json::TagEntry::setId(qint64 i)
{
	ensureTagEntryPrivate();
	Q_D(TagEntry);
	d->m_id = i;
}

const QString &Json::TagEntry::name(void) const
{
	Q_D(const TagEntry);
	if (Q_UNLIKELY(d == Q_NULLPTR)) {
		return nullString;
	}

	return d->m_name;
}

void Json::TagEntry::setName(const QString &n)
{
	ensureTagEntryPrivate();
	Q_D(TagEntry);
	d->m_name = n;
}

#ifdef Q_COMPILER_RVALUE_REFS
void Json::TagEntry::setName(QString &&n)
{
	ensureTagEntryPrivate();
	Q_D(TagEntry);
	d->m_name = ::std::move(n);
}
#endif /* Q_COMPILER_RVALUE_REFS */

const QString &Json::TagEntry::colour(void) const
{
	Q_D(const TagEntry);
	if (Q_UNLIKELY(d == Q_NULLPTR)) {
		return nullString;
	}

	return d->m_colour;
}

void Json::TagEntry::setColour(const QString &c)
{
	ensureTagEntryPrivate();
	Q_D(TagEntry);
	d->m_colour = c;
}

#ifdef Q_COMPILER_RVALUE_REFS
void Json::TagEntry::setColour(QString &&c)
{
	ensureTagEntryPrivate();
	Q_D(TagEntry);
	d->m_colour = ::std::move(c);
}
#endif /* Q_COMPILER_RVALUE_REFS */

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

	return d->m_description;
}

void Json::TagEntry::setDescription(const QString &de)
{
	ensureTagEntryPrivate();
	Q_D(TagEntry);
	d->m_description = de;
}

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

Json::TagEntry Json::TagEntry::fromJson(const QByteArray &json,
    bool *ok)
{
	QJsonObject jsonObj;
	if (!Helper::readRootObject(json, jsonObj)) {
		if (ok != Q_NULLPTR) {
			*ok = false;
		}
		return TagEntry();
	}

	return fromJsonVal(jsonObj, ok);
}

static const QString keyId("id");
static const QString keyName("name");
static const QString keyColour("colour");
static const QString keyDescription("description");

Json::TagEntry Json::TagEntry::fromJsonVal(const QJsonValue &jsonVal,
    bool *ok)
{
	TagEntry ste;

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

	{
		const QJsonObject jsonObj = jsonVal.toObject();

		{
			qint64 valInt = 0;
			if (Q_UNLIKELY(!Helper::readQint64String(jsonObj, keyId,
			        valInt, Helper::ACCEPT_VALID))) {
				goto fail;
			}
			ste.setId(valInt);
		}
		{
			QString valStr;
			if (Q_UNLIKELY(!Helper::readString(jsonObj, keyName,
			        valStr, Helper::ACCEPT_VALID))) {
				goto fail;
			}
			ste.setName(::std::move(valStr));
		}
		{
			QString valStr;
			if (Q_UNLIKELY(!Helper::readString(jsonObj, keyColour,
			        valStr, Helper::ACCEPT_VALID))) {
				goto fail;
			}
			ste.setColour(::std::move(valStr));
		}
		{
			QString valStr;
			if (Q_UNLIKELY(!Helper::readString(jsonObj, keyDescription,
			        valStr, Helper::ACCEPT_NULL))) {
				goto fail;
			}
			ste.setDescription(::std::move(valStr));
		}
	}

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

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

bool Json::TagEntry::toJsonVal(QJsonValue &jsonVal) const
{
	QJsonObject jsonObj;

	jsonObj.insert(keyId, (id() >= 0) ? QString::number(id()) : QJsonValue());
	jsonObj.insert(keyName, (!name().isEmpty()) ? name() : QJsonValue());
	jsonObj.insert(keyColour, (!colour().isEmpty()) ? colour() : QJsonValue());
	jsonObj.insert(keyDescription, (!description().isEmpty()) ? description() : QJsonValue());

	jsonVal = jsonObj;
	return true;
}

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

Json::TagEntryList::TagEntryList(void)
    : Object(),
    QList<TagEntry>()
{
}

Json::TagEntryList::TagEntryList(const QList<TagEntry> &other)
    : Object(),
    QList<TagEntry>(other)
{
}

#ifdef Q_COMPILER_RVALUE_REFS
Json::TagEntryList::TagEntryList(QList<TagEntry> &&other)
    : Object(),
    QList<TagEntry>(::std::move(other))
{
}
#endif /* Q_COMPILER_RVALUE_REFS */

Json::TagEntryList Json::TagEntryList::fromJson(const QByteArray &json,
    bool *ok)
{
	QJsonArray jsonArr;
	if (!Helper::readRootArray(json, jsonArr)) {
		if (ok != Q_NULLPTR) {
			*ok = false;
		}
		return TagEntryList();
	}

	return fromJsonVal(jsonArr, ok);
}

Json::TagEntryList Json::TagEntryList::fromJsonVal(
    const QJsonValue &jsonVal, bool *ok)
{
	TagEntryList tel;

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

	{
		const QJsonArray jsonArr = jsonVal.toArray();
		for (const QJsonValue &v : jsonArr) {
			bool iOk = false;
			tel.append(TagEntry::fromJsonVal(v, &iOk));
			if (Q_UNLIKELY(!iOk)) {
				goto fail;
			}
		}
	}

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

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

bool Json::TagEntryList::toJsonVal(QJsonValue &jsonVal) const
{
	QJsonArray arr;

	for (const TagEntry &te : *this) {
		QJsonValue v;
		if (Q_UNLIKELY(!te.toJsonVal(v))) {
			goto fail;
		}
		arr.append(v);
	}

	jsonVal = arr;
	return true;

fail:
	jsonVal = QJsonArray();
	return false;
}

#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
size_t Json::qHash(const TagEntry &key, size_t seed)
#else /* < Qt-6.0 */
uint Json::qHash(const TagEntry &key, uint seed)
#endif /* >= Qt-6.0 */
{
	return ::qHash(key.id(), seed);
}
