/*
 * Copyright (C) 2014-2026 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 <QJsonObject>
#include <QString>

#include "src/datovka_shared/json/helper.h"
#include "src/json/note_assignment.h"
#include "src/json/note_assignment_hash.h"

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

	return fromJsonVal(jsonArr, ok);
}

Json::NoteAssignmentHash Json::NoteAssignmentHash::fromJsonVal(
    const QJsonValue &jsonVal, bool *ok)
{
	NoteAssignmentHash h;

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

	{
		const QJsonArray jsonArr = jsonVal.toArray();
		for (const QJsonValue &v : jsonArr) {
			bool iOk = false;
			NoteAssignment ta = NoteAssignment::fromJsonVal(v, &iOk);
			if (Q_UNLIKELY(!iOk)) {
				goto fail;
			}
			h.insert(MsgId1(ta.testEnv(), ta.dmId()), ta.entries());
		}
	}

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

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

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

	for (const MsgId1 &key : keys()) {
		QJsonValue v;
		if (Q_UNLIKELY(!NoteAssignment(key.testEnv(), key.dmId(), operator[](key)).toJsonVal(v))) {
			goto fail;
		}
		arr.append(v);
	}

	jsonVal = arr;
	return true;

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