/*
 * 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 <QDateTime>
#include <QDir>
#include <QMenu>
#include <QTimeZone>

#include "src/datovka_shared/crypto/crypto_funcs.h"
#include "src/datovka_shared/crypto/crypto_wrapped.h"
#include "src/datovka_shared/html/html_export.h"
#include "src/datovka_shared/isds/type_conversion.h"
#include "src/datovka_shared/isds/type_description.h"
#include "src/datovka_shared/log/log.h"
#include "src/datovka_shared/settings/prefs.h"
#include "src/datovka_shared/utility/date_time.h"
#include "src/dimensions/dimensions.h"
#include "src/global.h"
#include "src/gui/dlg_import_zfo.h"
#include "src/gui/dlg_signature_detail.h"
#include "src/gui/dlg_view_zfo.h"
#include "src/gui/icon_container.h"
#include "src/io/filesystem.h"
#include "src/model_interaction/attachment_interaction.h"
#include "src/model_interaction/view_interaction.h"
#include "src/settings/prefs_specific.h"
#include "src/views/table_home_end_filter.h"
#include "src/views/table_tab_ignore_filter.h"
#include "ui_dlg_view_zfo.h"

static const QString dlgName("view_zfo");
static const QString attachmentTableName("attachment_list");
static const QString dlgSplitterName("attachment");

DlgViewZfo::DlgViewZfo(const Isds::Message &message, enum Isds::LoadType zfoType,
    const QString &errMsg, QWidget *parent)
    : QDialog(parent),
    m_ui(new (::std::nothrow) Ui::DlgViewZfo),
    m_message(message),
    m_zfoType(zfoType),
    m_attachmentModel(false, this)
{
	m_ui->setupUi(this);
	/* Tab order is defined in UI file. */

	/* Set default line height for table views/widgets. */
	m_ui->attachmentTable->setNarrowedLineHeight();
	m_ui->attachmentTable->horizontalHeader()->setDefaultAlignment(Qt::AlignVCenter | Qt::AlignLeft);

	if (Q_UNLIKELY(m_message.isNull())) {
		/* Just show error message. */
		m_ui->attachmentTable->hide();
		m_ui->envelopeTextEdit->setHtml(
		    "<h3>" + tr("Error parsing content") + "</h3><br/>" +
		    errMsg);
		m_ui->envelopeTextEdit->setReadOnly(true);
		m_ui->signatureDetailsButton->setEnabled(false);
		return;
	}

	setUpDialogue();
}

DlgViewZfo::~DlgViewZfo(void)
{
	PrefsSpecific::setDlgTblRelColWidths(*GlobInstcs::prefsPtr,
	    dlgName, attachmentTableName,
	    Dimensions::relativeTableColumnWidths(m_ui->attachmentTable));
	PrefsSpecific::setDlgTblColSortOrder(*GlobInstcs::prefsPtr,
	    dlgName, attachmentTableName,
	    Dimensions::tableColumnSortOrder(m_ui->attachmentTable));

	if (!m_ui->attachmentTable->isHidden()) {
		/* Don't store splitter size if attachment table is hidden. */
		PrefsSpecific::setDlgSplitterSize(*GlobInstcs::prefsPtr,
		    dlgName, dlgSplitterName,
		    Dimensions::splitterSize(m_ui->splitter));
	}

	delete m_ui;
}

void DlgViewZfo::view(const QString &zfoFileName, QWidget *parent)
{
	if (Q_UNLIKELY(zfoFileName.isEmpty())) {
		Q_ASSERT(0);
		return;
	}

	enum Isds::LoadType zfoType = Isds::LT_ANY;

	/* Load message ZFO. */
	const Isds::Message message = Isds::parseZfoFile(zfoFileName, zfoType);

	DlgViewZfo dlg(message, zfoType,
	    tr("Cannot parse the content of file '%1'.")
	        .arg(QDir::toNativeSeparators(zfoFileName)),
	    parent);

	const QSize dfltSize = dlg.size();
	{
		const QSize newSize = Dimensions::dialogueSize(&dlg,
		    PrefsSpecific::dlgSize(*GlobInstcs::prefsPtr, dlgName),
		    dfltSize);
		if (newSize.isValid()) {
			dlg.resize(newSize);
		}
	}

	dlg.exec();

	PrefsSpecific::setDlgSize(*GlobInstcs::prefsPtr, dlgName,
	    dlg.size(), dfltSize);
}

void DlgViewZfo::view(const QByteArray &zfoData, QWidget *parent)
{
	enum Isds::LoadType zfoType = Isds::LT_ANY;

	/* Load raw message. */
	const Isds::Message message = Isds::parseZfoData(zfoData, zfoType);

	DlgViewZfo dlg(message, zfoType,
	    tr("Cannot parse the content of message."), parent);

	const QSize dfltSize = dlg.size();
	{
		const QSize newSize = Dimensions::dialogueSize(&dlg,
		    PrefsSpecific::dlgSize(*GlobInstcs::prefsPtr, dlgName),
		    dfltSize);
		if (newSize.isValid()) {
			dlg.resize(newSize);
		}
	}

	dlg.exec();

	PrefsSpecific::setDlgSize(*GlobInstcs::prefsPtr, dlgName,
	    dlg.size(), dfltSize);
}

void DlgViewZfo::showEvent(QShowEvent *event)
{
	QDialog::showEvent(event);

	Dimensions::setRelativeTableColumnWidths(m_ui->attachmentTable,
	    PrefsSpecific::dlgTblRelColWidths(*GlobInstcs::prefsPtr,
	    dlgName, attachmentTableName));
	Dimensions::setTableColumnSortOrder(m_ui->attachmentTable,
	    PrefsSpecific::dlgTblColSortOrder(*GlobInstcs::prefsPtr,
	    dlgName, attachmentTableName));

	Dimensions::setSplitterSize(m_ui->splitter,
	    PrefsSpecific::dlgSplitterSize(*GlobInstcs::prefsPtr,
	    dlgName, dlgSplitterName));
}

void DlgViewZfo::attachmentItemRightClicked(const QPoint &point)
{
	QModelIndex index(m_ui->attachmentTable->indexAt(point));
	QMenu *menu = new (::std::nothrow) QMenu(this);
	if (Q_UNLIKELY(Q_NULLPTR == menu)) {
		Q_ASSERT(0);
		return;
	}

	/* Detects selection of multiple attachments. */
	QModelIndexList indexes(
	    ViewInteraction::selectedRows(*m_ui->attachmentTable,
	        AttachmentTblModel::FNAME_COL));

	if (index.isValid()) {
		menu->addAction(
		    IconContainer::construcIcon(IconContainer::ICON_APP_FOLDER),
		    tr("Open attachment"),
		    this, SLOT(openSelectedAttachment()))->setEnabled(indexes.size() == 1);
		{
			const QIcon ico(
			    IconContainer::construcIcon(IconContainer::ICON_ATTACHMENT_SAVE));
			menu->addAction(ico, tr("Save attachment"), this,
			    SLOT(saveSelectedAttachmentsToFile()))->
			        setEnabled(indexes.size() == 1);
			menu->addAction(ico, tr("Save attachments"), this,
			    SLOT(saveSelectedAttachmentsIntoDirectory()))->
			        setEnabled(indexes.size() > 1);
		}
	} else {
		/* Do nothing. */
	}
	menu->exec(QCursor::pos());
	menu->deleteLater();
}

void DlgViewZfo::saveSelectedAttachmentsToFile(void)
{
	debugSlotCall();

	AttachmentInteraction::saveAttachmentsToFile(this,
	    *m_ui->attachmentTable);
}

void DlgViewZfo::saveSelectedAttachmentsIntoDirectory(void)
{
	debugSlotCall();

	AttachmentInteraction::saveAttachmentsToDirectory(this,
	    *m_ui->attachmentTable,
	    ViewInteraction::selectedRows(*m_ui->attachmentTable,
	        AttachmentTblModel::FNAME_COL));
}

void DlgViewZfo::openSelectedAttachment(const QModelIndex &index)
{
	debugSlotCall();

	AttachmentInteraction::openAttachment(this, *m_ui->attachmentTable,
	    index);
}

void DlgViewZfo::showSignatureDetailsDlg(void)
{
	Q_ASSERT(!m_message.isNull());
	Q_ASSERT(!m_message.envelope().isNull());

	DlgSignatureDetail::detail(m_message.raw(),
	    m_message.envelope().dmQTimestamp(), this);
}

void DlgViewZfo::setUpDialogue(void)
{
	/* TODO -- Adjust splitter sizes. */

	if (Isds::LT_DELIVERY == m_zfoType) {
		m_ui->attachmentTable->hide();
		m_ui->envelopeTextEdit->setHtml(
		    deliveryDescriptionHtml(m_message.raw(),
		        m_message.envelope().dmQTimestamp()));
		m_ui->envelopeTextEdit->setReadOnly(true);

	} else {
		m_ui->attachmentTable->setEnabled(true);
		m_ui->attachmentTable->show();
		m_attachmentModel.setMessage(m_message);
		m_attachmentModel.setHeader();
		m_ui->envelopeTextEdit->setHtml(
		    messageDescriptionHtml(m_message.raw(),
		    m_message.envelope().dmQTimestamp()));
		m_ui->envelopeTextEdit->setReadOnly(true);

		/* Attachment list. */
		m_ui->attachmentTable->setModel(&m_attachmentModel);
		/* First three columns contain hidden data. */
		m_ui->attachmentTable->setColumnHidden(
		    AttachmentTblModel::ATTACHID_COL, true);
		m_ui->attachmentTable->setColumnHidden(
		    AttachmentTblModel::MSGID_COL, true);
		m_ui->attachmentTable->setColumnHidden(
		    AttachmentTblModel::BINARY_CONTENT_COL, true);
		m_ui->attachmentTable->setColumnHidden(
		    AttachmentTblModel::MIME_COL, true);
		m_ui->attachmentTable->setColumnHidden(
		    AttachmentTblModel::FPATH_COL, true);
		m_ui->attachmentTable->setColumnHidden(
		    AttachmentTblModel::CREATED_FROM_TEXT_COL, true);
		m_ui->attachmentTable->resizeColumnToContents(
		    AttachmentTblModel::FNAME_COL);

		m_ui->attachmentTable->setContextMenuPolicy(
		    Qt::CustomContextMenu);
		connect(m_ui->attachmentTable,
		    SIGNAL(customContextMenuRequested(QPoint)),
		    this, SLOT(attachmentItemRightClicked(QPoint)));
		connect(m_ui->attachmentTable,
		    SIGNAL(doubleClicked(QModelIndex)),
		    this, SLOT(openSelectedAttachment(QModelIndex)));

		m_ui->attachmentTable->installEventFilter(
		    new (::std::nothrow) TableHomeEndFilter(m_ui->attachmentTable));
		m_ui->attachmentTable->installEventFilter(
		    new (::std::nothrow) TableTabIgnoreFilter(m_ui->attachmentTable));
	}

	/* Signature details. */
	connect(m_ui->signatureDetailsButton, SIGNAL(clicked()), this,
	    SLOT(showSignatureDetailsDlg()));
}

QString DlgViewZfo::messageDescriptionHtml(const QByteArray &msgDER,
    const QByteArray &tstDER) const
{
	if (Q_UNLIKELY(m_message.isNull())) {
		Q_ASSERT(0);
		return QString();
	}

	const Isds::Envelope &envelope(m_message.envelope());
	if (Q_UNLIKELY(envelope.isNull())) {
		Q_ASSERT(0);
		return QString();
	}

	return htmlMarginsApp("",
	    Html::Export::htmlMessageInfoApp(envelope,
	    QByteArray(),
	    QStringList(),
	    true, false, true) + htmlSignatureInfo(msgDER, tstDER));
}

QString DlgViewZfo::deliveryDescriptionHtml(const QByteArray &msgDER,
    const QByteArray &tstDER) const
{
	if (Q_UNLIKELY(m_message.isNull())) {
		Q_ASSERT(0);
		return QString();
	}

	const Isds::Envelope &envelope(m_message.envelope());
	if (Q_UNLIKELY(envelope.isNull())) {
		Q_ASSERT(0);
		return QString();
	}

	return htmlMarginsApp("",
	    Html::Export::htmlMessageInfoApp(envelope,
	    QByteArray(),
	    QStringList(),
	    true, false, true) + htmlSignatureInfo(msgDER, tstDER));
}

QString DlgViewZfo::htmlSignatureInfo(const QByteArray &msgDER,
    const QByteArray &tstDER)
{
	/* TODO -- Remove this function parameter if not really needed. */
	Q_UNUSED(tstDER);

	QString sigResStr,certResStr, tsResStr;

	if (1 == raw_msg_verify_signature(msgDER.constData(), msgDER.size(), 0, 0)) {
		sigResStr = tr("Valid");
	} else {
		sigResStr = tr("Invalid")  + " -- " +
		    tr("Message signature and content do not correspond!");
	}

	if (1 == raw_msg_verify_signature_date(msgDER.constData(), msgDER.size(),
#if (QT_VERSION >= QT_VERSION_CHECK(5, 8, 0))
		QDateTime::currentDateTime().toSecsSinceEpoch(),
#else /* < Qt-5.8 */
	        QDateTime::currentDateTime().toMSecsSinceEpoch() / 1000,
#endif /* >= Qt-5.8 */
	        0)) {
		certResStr = tr("Valid");
	} else {
		certResStr = tr("Invalid");
	}
	if (!PrefsSpecific::checkCrl(*GlobInstcs::prefsPtr)) {
		certResStr += " (" +
		    tr("Certificate revocation check is turned off!") +
		    ")";
	}

	QDateTime tstTime;
	const enum TstEntries::Validity valid = TstEntries::latestTstValid(msgDER, tstTime);
	switch (valid) {
	case TstEntries::MISSING:
		tsResStr = tr("Missing");
		break;
	case TstEntries::VALID:
		tsResStr = tr("Valid");
		break;
	case TstEntries::INVALID:
		tsResStr = tr("Invalid");
		break;
	default:
		break;
	}
	if (tstTime.isValid()) {
		tsResStr += " (" + tstTime.toString(Utility::dateTimeDisplayFormat) + " " +
		    tstTime.timeZone().abbreviation(tstTime) + ")";
	}

	return Html::Export::htmlSignatureInfoApp(sigResStr, certResStr,
	    tsResStr);
}
