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

#if defined(__APPLE__) || defined(__clang__)
#  define __USE_C99_MATH
#  define _Bool bool
#else /* !__APPLE__ */
#  include <stdbool.h>
#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 Guess the content of the data portion.
 *
 * @param[in] data Raw message data.
 * @param[in] size Raw data length.
 * @return ZFO type, RT_UNKNOWN on any error.
 */
static inline
enum Isds::Type::RawType _guessRawType(const char *data, const qsizetype size)
{
	isds_error status;
	isds_raw_type iRawType;
	struct isds_ctx *iDummySession = NULL;
	enum Isds::Type::RawType rawType = Isds::Type::RT_UNKNOWN;
	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, &iRawType, data, size);
	if (Q_UNLIKELY(IE_SUCCESS != status)) {
		logErrorNL("%s", "Cannot guess raw content type.");
		goto fail;
	}

	rawType = Isds::libisdsRawType2RawType(iRawType, &iOk);
	if (Q_UNLIKELY(!iOk)) {
		logErrorNL("%s", "Cannot convert raw content type.");
		/* Raw type is Type::RT_UNKNOWN, fail follows. */
	}

fail:
	if (NULL != iDummySession) {
		isds_ctx_free(&iDummySession);
	}
	return rawType;
}

enum Isds::Type::RawType Isds::guessDataRawType(const QByteArray &rawMsgData)
{
	return _guessRawType(rawMsgData.constData(), rawMsgData.size());
}

enum Isds::Type::RawType Isds::guessFileRawType(const QString &fName)
{
	enum Isds::Type::RawType rawType = Isds::Type::RT_UNKNOWN;

	if (Q_UNLIKELY(fName.isEmpty())) {
		Q_ASSERT(0);
		goto fail;
	}

	{
		qint64 fSize = 0;
		const char *fData = NULL;

		QFile file(fName);
		if (Q_UNLIKELY(!file.open(QIODevice::ReadOnly))) {
			logErrorNL("Cannot open file '%s'.",
			    fName.toUtf8().constData());
			goto fail;
		}
		fSize = file.size();
		fData = (char *)file.map(0, fSize);
		if (Q_UNLIKELY(fData == Q_NULLPTR)) {
			logError("Cannot map file '%s' into memory.",
			    fName.toUtf8().constData());
			goto fail;
		}

		rawType = _guessRawType(fData, fSize);

		file.close(); /* File can be closed but object must remain. */
	}

fail:
	return rawType;
}

/*!
 * @brief Guess the content of the data portion.
 *
 * @param[in] data Raw message data.
 * @param[in] size Raw data length.
 * @param[out] attachTotal Total of attachment sizes.
 * @return ZFO type, RT_UNKNOWN on any error.
 */
static inline
enum Isds::Type::RawType _guessRawTypeAttachTotal(const char *data,
    const qsizetype size, qint64 &attachTotal)
{
	isds_error status;
	isds_raw_type iRawType;
	struct isds_ctx *iDummySession = NULL;
	struct isds_message *iMessage = NULL;
	enum Isds::Type::RawType rawType = Isds::Type::RT_UNKNOWN;
	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, &iRawType, data, size);
	if (Q_UNLIKELY(IE_SUCCESS != status)) {
		logErrorNL("%s", "Cannot guess raw content type.");
		goto fail;
	}

	switch (iRawType) {
	case RAWTYPE_INCOMING_MESSAGE:
	case RAWTYPE_PLAIN_SIGNED_INCOMING_MESSAGE:
	case RAWTYPE_CMS_SIGNED_INCOMING_MESSAGE:
	case RAWTYPE_PLAIN_SIGNED_OUTGOING_MESSAGE:
	case RAWTYPE_CMS_SIGNED_OUTGOING_MESSAGE:
		status = isds_load_message(iDummySession, iRawType,
		    data, size, &iMessage, BUFFER_COPY);
		if ((IE_SUCCESS == status) && (iMessage != NULL)) {
			qint64 total = 0;
			const struct isds_list *item = iMessage->documents;
			while (item != NULL) {
				const struct isds_document *id = (struct isds_document *)item->data;

				if ((id != NULL) && (id->data != NULL)) {
					total += id->data_length;
				}

				item = item->next;
			}
			attachTotal = total;
		} else {
			attachTotal = 0;
		}
		break;
	case RAWTYPE_DELIVERYINFO:
	case RAWTYPE_PLAIN_SIGNED_DELIVERYINFO:
	case RAWTYPE_CMS_SIGNED_DELIVERYINFO:
		attachTotal = 0;
		break;
	default:
		attachTotal = 0;
		break;
	}

	rawType = Isds::libisdsRawType2RawType(iRawType, &iOk);
	if (Q_UNLIKELY(!iOk)) {
		logErrorNL("%s", "Cannot convert raw content type.");
		/* Raw type is Type::RT_UNKNOWN, fail follows. */
	}

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

enum Isds::Type::RawType Isds::guessDataRawTypeAttachTotal(
    const QByteArray &rawMsgData, qint64 &attachTotal)
{
	return _guessRawTypeAttachTotal(rawMsgData.constData(),
	    rawMsgData.size(), attachTotal);
}

enum Isds::Type::RawType Isds::guessFileRawTypeAttachTotal(const QString &fName,
    qint64 &attachTotal)
{
	enum Isds::Type::RawType rawType = Isds::Type::RT_UNKNOWN;

	if (Q_UNLIKELY(fName.isEmpty())) {
		Q_ASSERT(0);
		goto fail;
	}

	{
		qint64 fSize = 0;
		const char *fData = NULL;

		QFile file(fName);
		if (Q_UNLIKELY(!file.open(QIODevice::ReadOnly))) {
			logErrorNL("Cannot open file '%s'.",
			    fName.toUtf8().constData());
			goto fail;
		}
		fSize = file.size();
		fData = (char *)file.map(0, fSize);
		if (Q_UNLIKELY(fData == Q_NULLPTR)) {
			logError("Cannot map file '%s' into memory.",
			    fName.toUtf8().constData());
			goto fail;
		}

		rawType = _guessRawTypeAttachTotal(fData, fSize, attachTotal);

		file.close(); /* File can be closed but object must remain. */
	}

fail:
	return rawType;
}

/*!
 * @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 iRawType;
	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, &iRawType, 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, iRawType,
		    data, size, &iMessage, BUFFER_COPY);
		isMessage = (IE_SUCCESS == status);
	}
	if ((!isMessage) && (zfoType != Isds::LT_MESSAGE)) {
		status = isds_load_delivery_info(iDummySession, iRawType,
		    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);
}

Isds::Hash Isds::computeDmHash(const Message &message,
    enum Type::HashAlg hashAlg)
{
	isds_error status;
	struct isds_ctx *iDummySession = NULL;
	isds_hash_algorithm iHashAlg;
	struct isds_message *iMessage = NULL;
	Isds::Hash hash;
	bool iOk = false;

	if (Q_UNLIKELY(Type::HA_UNKNOWN == hashAlg)) {
		logErrorNL("%s", "Invalid hash algorithm.");
		goto fail;
	}
	iHashAlg = (isds_hash_algorithm)hashAlg2libisdsHashAlg(hashAlg, &iOk);
	if (Q_UNLIKELY(!iOk)) {
		logErrorNL("%s", "Cannot convert hash algorithm.");
		goto fail;
	}

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

	iMessage = message2libisds(message, &iOk);
	if (Q_UNLIKELY((!iOk) || (NULL == iMessage))) {
		logErrorNL("%s", "Cannot convert message object.");
		goto fail;
	}

	status = isds_compute_message_hash(iDummySession, iMessage, iHashAlg);
	if (Q_UNLIKELY(IE_SUCCESS != status)) {
		logErrorNL("%s", "Cannot compute message hash.");
		goto fail;
	}

	hash = libisds2hash(iMessage->envelope->hash, &iOk);
	if (Q_UNLIKELY(!iOk)) {
		logErrorNL("%s", "Cannot convert hash.");
		goto fail;
	}

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