/*
 * 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.
 */

#if defined(__APPLE__) || defined(__clang__)
#  define __USE_C99_MATH
#  define _Bool bool
#else /* !__APPLE__ */
#  include <cstdbool>
#endif /* __APPLE__ */

#include <libdatovka/isds.h>
#include <QByteArray>
#include <QFile>
#include <QString>

#include <src/datovka_shared/compat_qt/misc.h> /* qsizetype */
#include "src/datovka_shared/log/log.h"
#include "src/isds/message_conversion.h"
#include "src/isds/message_functions.h"

/*!
 * @brief Creates a message from supplied raw CMS data.
 *
 * @param[in] data Raw message data.
 * @param[in] size Raw data length.
 * @param[in] zfoType Message or delivery info.
 * @return Return null message on error.
 */
static inline
Isds::Message _messageFromData(const char *data, const qsizetype size,
    enum Isds::LoadType zfoType)
{
	isds_error status;
	isds_raw_type rawType;
	struct isds_ctx *iDummySession = NULL;
	struct isds_message *iMessage = NULL;
	bool isMessage = false;
	Isds::Message message;
	bool iOk = false;

	iDummySession = isds_ctx_create();
	if (Q_UNLIKELY(NULL == iDummySession)) {
		logErrorNL("%s", "Cannot create dummy session.");
		goto fail;
	}

	status = isds_guess_raw_type(iDummySession, &rawType, data, size);
	if (Q_UNLIKELY(IE_SUCCESS != status)) {
		logErrorNL("%s", "Cannot guess message content type.");
		goto fail;
	}

	if (zfoType != Isds::LT_DELIVERY) {
		status = isds_load_message(iDummySession, rawType,
		    data, size, &iMessage, BUFFER_COPY);
		isMessage = (IE_SUCCESS == status);
	}
	if ((!isMessage) && (zfoType != Isds::LT_MESSAGE)) {
		status = isds_load_delivery_info(iDummySession, rawType,
		    data, size, &iMessage, BUFFER_COPY);
	}
	if (Q_UNLIKELY(IE_SUCCESS != status)) {
		logErrorNL("%s", "Cannot load message content.");
		goto fail;
	}

	message = Isds::libisds2message(iMessage, &iOk);
	if (Q_UNLIKELY(!iOk)) {
		logErrorNL("%s", "Cannot create message object.");
		/* Message is null, fail follows. */
	}

fail:
	if (NULL != iMessage) {
		isds_message_free(&iMessage);
	}
	if (NULL != iDummySession) {
		isds_ctx_free(&iDummySession);
	}
	return message;
}

Isds::Message Isds::messageFromData(const QByteArray &rawMsgData,
    enum LoadType zfoType)
{
	return _messageFromData(rawMsgData.constData(), rawMsgData.size(),
	    zfoType);
}

/*!
 * @brief Try loading ZFO data.
 *
 * @param[in] data Raw message data.
 * @param[in] size Raw data length.
 * @param[out] zfoType Detected ZFO file type.
 * @param[out] ok Set to true on success.
 * @return Return null message on error.
 */
static inline
Isds::Message _parseZfoData(const char *data, const qsizetype size,
    enum Isds::LoadType &zfoType, bool *ok)
{
	Isds::Message message = _messageFromData(data, size, Isds::LT_MESSAGE);
	if (!message.isNull()) {
		zfoType = Isds::LT_MESSAGE;
		if (ok != Q_NULLPTR) {
			*ok = true;
		}
	} else {
		message = _messageFromData(data, size, Isds::LT_DELIVERY);
		if (!message.isNull()) {
			zfoType = Isds::LT_DELIVERY;
			if (ok != Q_NULLPTR) {
				*ok = true;
			}
		}
	}
	if (Q_UNLIKELY(message.isNull())) {
		if (ok != Q_NULLPTR) {
			*ok = false;
		}
		logErrorNL("%s", "Cannot parse message data.");
	}

	return message;
}

Isds::Message Isds::parseZfoData(const QByteArray &rawMsgData,
    enum LoadType &zfoType, bool *ok)
{
	return _parseZfoData(rawMsgData.constData(), rawMsgData.size(),
	    zfoType, ok);
}

Isds::Message Isds::messageFromFile(const QString &fName, enum LoadType zfoType)
{
	if (Q_UNLIKELY(fName.isEmpty())) {
		Q_ASSERT(0);
		return Message();
	}

	QFile file(fName);
	if (Q_UNLIKELY(!file.open(QIODevice::ReadOnly))) {
		logErrorNL("Cannot open file '%s'.",
		    fName.toUtf8().constData());
		return Message();
	}
	qint64 fSize = file.size();
	const char *fData = (char *)file.map(0, fSize);
	if (Q_UNLIKELY(fData == Q_NULLPTR)) {
		logError("Cannot map file '%s' into memory.",
		    fName.toUtf8().constData());
	}
	file.close(); /* File can be closed but object must remain. */

	return _messageFromData(fData, fSize, zfoType);
}

Isds::Message Isds::parseZfoFile(const QString &fName, enum LoadType &zfoType,
    bool *ok)
{
	if (Q_UNLIKELY(fName.isEmpty())) {
		Q_ASSERT(0);
		if (ok != Q_NULLPTR) {
			*ok = true;
		}
		return Message();
	}

	QFile file(fName);
	if (Q_UNLIKELY(!file.open(QIODevice::ReadOnly))) {
		logErrorNL("Cannot open file '%s'.",
		    fName.toUtf8().constData());
		if (ok != Q_NULLPTR) {
			*ok = true;
		}
		return Message();
	}
	qint64 fSize = file.size();
	const char *fData = (char *)file.map(0, fSize);
	if (Q_UNLIKELY(fData == Q_NULLPTR)) {
		logError("Cannot map file '%s' into memory.",
		    fName.toUtf8().constData());
	}
	file.close(); /* File can be closed but object must remain. */

	return _parseZfoData(fData, fSize, zfoType, ok);
}
