/*
 * 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 <cinttypes>
#include <cstdlib>
#include <cstring>
#include <QThread>
#include <QVariant>

#include "src/datovka_shared/isds/error.h"
#include "src/datovka_shared/isds/type_description.h"
#include "src/datovka_shared/log/log.h"
#include "src/global.h"
#include "src/io/account_db.h"
#include "src/io/isds_sessions.h"
#include "src/io/message_db_set.h"
#include "src/isds/message_conversion.h"
#include "src/isds/services.h"
#include "src/isds/session.h"
#include "src/settings/accounts.h"
#include "src/worker/message_emitter.h"
#include "src/worker/task_send_message.h"

TaskSendMessage::ResultData::ResultData(void)
    : result(SM_ERR),
    errInfo(),
    dbIDRecipient(),
    recipientName(),
    isPDZ(false),
    dmId(-1)
{
}

TaskSendMessage::ResultData::ResultData(enum Result res, const QString &eInfo,
    const QString &recId, const QString &recName, bool pdz, qint64 mId)
    : result(res),
    errInfo(eInfo),
    dbIDRecipient(recId),
    recipientName(recName),
    isPDZ(pdz),
    dmId(mId)
{
}

TaskSendMessage::TaskSendMessage(const AcntIdDb &acntIdDb,
    const QString &transactId, const Isds::Message &message,
    const QString &recipientName, const QString &recipientAddress, bool isPDZ,
    bool isVodz, bool storeRawInDb, int processFlags,
    const QString &recMgmtHierarchyId)
    : QObject(),
    m_resultData(),
    m_acntIdDb(acntIdDb),
    m_transactId(transactId),
    m_message(message),
    m_recipientName(recipientName),
    m_recipientAddress(recipientAddress),
    m_isPDZ(isPDZ),
    m_isVodz(isVodz),
    m_storeRawInDb(storeRawInDb),
    m_processFlags(processFlags),
    m_recMgmtHierarchyId(recMgmtHierarchyId)
{
	Q_ASSERT(m_acntIdDb.isValid());
}

void TaskSendMessage::run(void)
{
	if (Q_UNLIKELY(!m_acntIdDb.isValid())) {
		Q_ASSERT(0);
		return;
	}

	logDebugLv0NL("Starting send message task in thread '%p'",
	    (void *) QThread::currentThreadId());

	/* ### Worker task begin. ### */

	Isds::Session *session =
	    GlobInstcs::isdsSessionsPtr->session(m_acntIdDb.username());
	if (Q_NULLPTR != session) {
		connect(session, SIGNAL(progress(qint64, qint64, qint64, qint64)),
		    this, SLOT(watchProgress(qint64, qint64, qint64, qint64)),
		    Qt::DirectConnection); /* Qt::DirectConnection because it must be executed immediatelly. */
	}

	sendMessage(m_acntIdDb, m_message, m_recipientName,
	    m_recipientAddress, m_isPDZ, m_isVodz, m_storeRawInDb, PL_SEND_MESSAGE,
	    &m_resultData);

	if (Q_NULLPTR != session) {
		session->disconnect(Q_NULLPTR, this, Q_NULLPTR);
	}

	emit GlobInstcs::msgProcEmitterPtr->uploadProgressFinished(
	    AcntId(m_acntIdDb.username(), m_acntIdDb.testing()),
	    m_transactId, m_resultData.result, m_resultData.errInfo,
	    QVariant());

	emit GlobInstcs::msgProcEmitterPtr->sendMessageFinished(
	    AcntId(m_acntIdDb.username(), m_acntIdDb.testing()),
	    m_transactId, m_resultData.result, m_resultData.errInfo,
	    m_resultData.dbIDRecipient, m_resultData.recipientName,
	    m_isPDZ, m_isVodz, m_resultData.dmId, m_processFlags, m_recMgmtHierarchyId);

	emit GlobInstcs::msgProcEmitterPtr->progressChange(PL_IDLE, 0);

	/* ### Worker task end. ### */

	logDebugLv0NL("Send message task finished in thread '%p'",
	    (void *) QThread::currentThreadId());
}

void TaskSendMessage::watchProgress(qint64 uploadTotal, qint64 uploadCurrent,
    qint64 downloadTotal, qint64 downloadCurrent)
{
	Q_UNUSED(downloadTotal);
	Q_UNUSED(downloadCurrent);

	emit GlobInstcs::msgProcEmitterPtr->uploadProgress(
	    AcntId(m_acntIdDb.username(), m_acntIdDb.testing()),
	    m_transactId, uploadTotal, uploadCurrent);
}

enum TaskSendMessage::Result TaskSendMessage::sendMessage(
    const AcntIdDb &acntIdDb, const Isds::Message &message,
    const QString &recipientName, const QString &recipientAddress, bool isPDZ,
    bool isVodz, bool storeRawInDb, const QString &progressLabel,
    ResultData *resultData)
{
#define TRANSACTION_ENABLE true
	Q_ASSERT(acntIdDb.isValid());

	emit GlobInstcs::msgProcEmitterPtr->progressChange(progressLabel, 0);

	enum Result ret = SM_ERR;
	qint64 dmId = -1;
	Isds::Session *session = Q_NULLPTR;
	QString isdsError, isdsLongError;
	Isds::Error err;

	session = GlobInstcs::isdsSessionsPtr->session(acntIdDb.username());
	if (Q_UNLIKELY(Q_NULLPTR == session)) {
		logErrorNL("Missing active session for username '%s'.",
		    acntIdDb.username().toUtf8().constData());
		ret = SM_ERR;
		goto fail;
	}

	emit GlobInstcs::msgProcEmitterPtr->progressChange(progressLabel, 40);

	if (Q_UNLIKELY(GlobInstcs::req_halt)) {
		ret = SM_ABORTED;
		goto fail;
	}

	if (Q_UNLIKELY(message.isNull())) {
		logErrorNL("%s", "Cannot send null message.");
		ret = SM_ERR;
		goto fail;
	}

	logInfoNL("Sending message from user '%s'.",
	    acntIdDb.username().toUtf8().constData());

	if (isVodz) {
		err = Isds::Service::createBigMessage(session, message, dmId);
	} else {
		err = Isds::Service::createMessage(session, message, dmId);
	}

	if (Q_UNLIKELY(err.code() != Isds::Type::ERR_SUCCESS)) {
		isdsError = Isds::Description::descrError(err.code());
		isdsLongError = err.longDescr();
		logErrorNL("Sending message returned status %d: '%s' '%s'.",
		    err.code(), isdsError.toUtf8().constData(),
		    isdsLongError.toUtf8().constData());
		ret = SM_ISDS_ERROR;
		goto fail;
	}

	emit GlobInstcs::msgProcEmitterPtr->progressChange(progressLabel, 70);

	if (Q_UNLIKELY(GlobInstcs::req_halt)) {
		ret = SM_ABORTED;
		goto fail;
	}

	/* Store sent message to database */
	{
		MessageDb *messageDb = acntIdDb.messageDbSet()->accessMessageDb(
		    message.envelope().dmDeliveryTime(), true);
		if (Q_UNLIKELY(Q_NULLPTR == messageDb)) {
			Q_ASSERT(0);
			ret = SM_DB_INS_ERR;
			goto fail;
		}

		Q_ASSERT(dmId >= 0);

		const QString acntDbKey(AccountDb::keyFromLogin(acntIdDb.username()));

		/* Insert message envelope into database */
		Isds::Envelope envelope = message.envelope();
		envelope.setDmId(dmId);
		envelope.setDbIDSender(GlobInstcs::accntDbPtr->dbId(acntDbKey));
		envelope.setDmSender(GlobInstcs::accntDbPtr->senderNameGuess(acntDbKey));
		envelope.setDmRecipient(recipientName);
		envelope.setDmRecipientAddress(recipientAddress);
		envelope.setDmMessageStatus(Isds::Type::MS_POSTED);

		if (isVodz) {
			envelope.setDmVODZ(Isds::Type::BOOL_TRUE);
			envelope.setAttsNum(message.documents().size() + message.extFiles().size());
		}

		if (!messageDb->insertMessageEnvelope(envelope,
		    QString(), MessageDirection::MSG_SENT, TRANSACTION_ENABLE)) {
			logErrorNL(
			    "Cannot insert newly sent message '%" PRId64 "' into database.",
			    UGLY_QINT64_CAST dmId);
			ret = SM_DB_INS_ERR;
			goto fail;
		}

		emit GlobInstcs::msgProcEmitterPtr->progressChange(
		    progressLabel, 80);

		if (Q_UNLIKELY(GlobInstcs::req_halt)) {
			ret = SM_ABORTED;
			goto fail;
		}

		if (!isVodz) {
			/* Insert message attachments into database */
			messageDb->insertOrUpdateMessageAttachments(storeRawInDb,
			    dmId, message.documents(), TRANSACTION_ENABLE);
		}

		emit GlobInstcs::msgProcEmitterPtr->progressChange(
		    progressLabel, 90);
	}

	ret = SM_SUCCESS;

	emit GlobInstcs::msgProcEmitterPtr->progressChange(progressLabel, 100);

fail:
	if (Q_NULLPTR != resultData) {
		resultData->result = ret;
		resultData->dbIDRecipient = message.envelope().dbIDRecipient();
		resultData->recipientName = recipientName;
		resultData->dmId = dmId;
		resultData->isPDZ = isPDZ;
		resultData->errInfo =
		    (!isdsError.isEmpty() || !isdsLongError.isEmpty()) ?
		        isdsError + " " + isdsLongError : ""; 
	}

	return ret;
#undef TRANSACTION_ENABLE
}
