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

#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/isds_sessions.h"
#include "src/isds/qt_signal_slot.h"
#include "src/isds/services.h"
#include "src/isds/session.h"
#include "src/worker/message_emitter.h"
#include "src/worker/task_upload_attachment.h"

TaskUploadAttachment::TaskUploadAttachment(const AcntId &acntId,
    const Isds::DmFile &dmFile, const QString &transactId)
    : QObject(),
    m_result(UPLOAD_ERROR),
    m_isdsError(),
    m_isdsLongError(),
    m_dmAtt(),
    m_acntId(acntId),
    m_dmFile(dmFile),
    m_transactId(transactId)
{
	Q_ASSERT(m_acntId.isValid());
}

#ifdef Q_COMPILER_RVALUE_REFS
TaskUploadAttachment::TaskUploadAttachment(const AcntId &acntId,
    Isds::DmFile &&dmFile, const QString &transactId)
    : QObject(),
    m_result(UPLOAD_ERROR),
    m_isdsError(),
    m_isdsLongError(),
    m_dmAtt(),
    m_acntId(acntId),
    m_dmFile(::std::move(dmFile)),
    m_transactId(transactId)
{
	Q_ASSERT(m_acntId.isValid());
}
#endif /* Q_COMPILER_RVALUE_REFS */

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

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

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

	Isds::Session *session = GlobInstcs::isdsSessionsPtr->session(m_acntId.username());
	if (Q_NULLPTR != session) {
		connect(session, SIGNAL(progress(qint64, qint64, qint64, qint64)),
		    this, SLOT(watchProgress(qint64, qint64, qint64, qint64)));
	}

	m_result = uploadAttachment(m_acntId, m_dmFile, m_dmAtt, m_isdsError,
	    m_isdsLongError);

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

	emit GlobInstcs::msgProcEmitterPtr->uploadProgressFinished(m_acntId,
	    m_transactId, m_result, m_isdsError + " " + m_isdsLongError,
	    QVariant::fromValue(m_dmAtt));

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

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

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

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

	emit GlobInstcs::msgProcEmitterPtr->uploadProgress(m_acntId,
	    m_transactId, uploadTotal, uploadCurrent);
}

enum TaskUploadAttachment::Result TaskUploadAttachment::uploadAttachment(
    const AcntId &acntId, const Isds::DmFile &dmFile, Isds::DmAtt &dmAtt,
    QString &error, QString &longError)
{
	Q_ASSERT(acntId.isValid());

	if (Q_UNLIKELY(dmFile.isNull() || dmFile.binaryContent().isEmpty())) {
		return UPLOAD_DATA_ERROR;
	}

	Isds::Session *session = GlobInstcs::isdsSessionsPtr->session(acntId.username());
	if (Q_UNLIKELY(Q_NULLPTR == session)) {
		logErrorNL("Missing active session for username '%s'.",
		    acntId.username().toUtf8().constData());
		return UPLOAD_ERROR;
	}

	Isds::Error err = Isds::Service::uploadAttachment(session, dmFile,
	    dmAtt);
	if (Q_UNLIKELY(err.code() != Isds::Type::ERR_SUCCESS)) {
		error = Isds::Description::descrError(err.code());
		longError = err.longDescr();
		logErrorNL("Error upload attachment: '%s'.",
		    longError.toUtf8().constData());
		return UPLOAD_ISDS_ERROR;
	}

	return UPLOAD_SUCCESS;
}
