/*
 * 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 <QJsonArray>
#include <QJsonValue>

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

Json::Int64StringList::Int64StringList(void)
    : Object(),
    QList<qint64>()
{
}

Json::Int64StringList::Int64StringList(const QList<qint64> &other)
    : Object(),
    QList<qint64>(other)
{
}

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

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

	return fromJsonVal(jsonArr, ok);
}

Json::Int64StringList Json::Int64StringList::fromJsonVal(
    const QJsonValue &jsonVal, bool *ok)
{
	Int64StringList sisl;

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

	{
		const QJsonArray jsonArr = jsonVal.toArray();
		for (const QJsonValue &v : jsonArr) {
			qint64 readVal;
			if (Helper::valToQint64String(v, readVal,
			        Helper::ACCEPT_VALID)) {
				sisl.append(readVal);
			} else {
				goto fail;
			}
		}
	}

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

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

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

	for (qint64 num : *this) {
		arr.append(QString::number(num));
	}

	jsonVal = arr;
	return true;
}
