/*
 * 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 <QChar>
#include <QDir>
#include <QFileInfo>

#include "src/datovka_shared/isds/message_interface.h"
#include "src/global.h"
#include "src/io/export_file_name.h"
#include "src/io/filesystem.h"
#include "src/settings/prefs_specific.h"

#define FILE_NAME_MAX_LENGTH 255

/*!
 * @brief Replace some problematic characters when constructing a file name
 *        and truncate file name length.
 *
 * @param[in] s String to be modified.
 * @return Modified file name and its length.
 */
static
QString replaceNameCharsAndTruncate(const QString &s)
{
	QString str(s);
	int maxLength =
	    PrefsSpecific::exportedNamesParamMaxLength(*GlobInstcs::prefsPtr);

	/*
	 * Intentionally also replace characters that could be interpreted
	 * as directory separators.
	 */
	str.replace(QChar(' '), QChar('-'))
	    .replace(QChar('\t'), QChar('-'))
	    .replace(QChar('/'), QChar('-'))
	    .replace(QChar('\\'), QChar('-'))
	    .remove(QChar('\n'))
	    .truncate(maxLength);
	return str;
}

/*!
 * @brief Truncated file name on 255 chars.
 *
 * @param[in] fileName File name to be modified.
 * @return Truncated file name.
 */
static
QString truncateFileName(const QString &fileName)
{
	QFileInfo fi(fileName);

	QString fn = fi.fileName();
	/* -6 truncate suffix with dot. */
	fn.truncate(FILE_NAME_MAX_LENGTH-6);

	QString newFileName;
	if (!fi.path().isEmpty()) {
		newFileName.append(fi.path());
		newFileName.append(QDir::separator());
	}
	newFileName.append(fn);
	if (!fi.suffix().isEmpty()) {
		newFileName.append(".");
		newFileName.append(fi.suffix());
	}
	return newFileName;
}

QString fileSubPathFromFormat(QString format, bool prohibitDirSep, qint64 dmId,
    const QString &dbId, const QString &userName, QString accountName,
    const QString &attachName, const Isds::Envelope &envelope,
    const QString &dmTypePrefix, const QString &suffix)
{
	if (format.isEmpty()) {
		format = DEFAULT_TMP_FORMAT;
	}

	if (prohibitDirSep) {
		format = QFileInfo(format).fileName();
	}

	if (!suffix.isEmpty()) {
		format.append(suffix);
	}

	/* Construct list of format attributes that can be replaced. */
	typedef QPair<QString, QString> StringPairType;
	QList<StringPairType> knowAtrrList;

	/* Account parameters. */
	knowAtrrList.append(StringPairType(QStringLiteral("%<AN>"),
	    replaceNameCharsAndTruncate(accountName)));
	knowAtrrList.append(StringPairType(QStringLiteral("%<AB>"), dbId));
	knowAtrrList.append(StringPairType(QStringLiteral("%<AU>"), userName));

	/* Acceptance time parameters. */
	if (!envelope.dmAcceptanceTime().isNull()
	        && envelope.dmAcceptanceTime().isValid()) {

		knowAtrrList.append(StringPairType(QStringLiteral("%<AY>"),
		    envelope.dmAcceptanceTime().date().toString("yyyy")));
		knowAtrrList.append(StringPairType(QStringLiteral("%<Ay>"),
		    envelope.dmAcceptanceTime().date().toString("yy")));
		knowAtrrList.append(StringPairType(QStringLiteral("%<AM>"),
		    envelope.dmAcceptanceTime().date().toString("MM")));
		knowAtrrList.append(StringPairType(QStringLiteral("%<AD>"),
		    envelope.dmAcceptanceTime().date().toString("dd")));
		knowAtrrList.append(StringPairType(QStringLiteral("%<Ah>"),
		    envelope.dmAcceptanceTime().time().toString("hh")));
		knowAtrrList.append(StringPairType(QStringLiteral("%<Am>"),
		    envelope.dmAcceptanceTime().time().toString("mm")));

		/* Old format. */
		knowAtrrList.append(StringPairType(QStringLiteral("%Y"),
		    envelope.dmAcceptanceTime().date().toString("yyyy")));
		knowAtrrList.append(StringPairType(QStringLiteral("%M"),
		    envelope.dmAcceptanceTime().date().toString("MM")));
		knowAtrrList.append(StringPairType(QStringLiteral("%D"),
		    envelope.dmAcceptanceTime().date().toString("dd")));
		knowAtrrList.append(StringPairType(QStringLiteral("%h"),
		    envelope.dmAcceptanceTime().time().toString("hh")));
		knowAtrrList.append(StringPairType(QStringLiteral("%m"),
		    envelope.dmAcceptanceTime().time().toString("mm")));
	} else {
		format = format.remove(QStringLiteral("%<AY>"))
		.remove(QStringLiteral("%<AM>"))
		.remove(QStringLiteral("%<AD>"))
		.remove(QStringLiteral("%<Ah>"))
		.remove(QStringLiteral("%<Am>"));

		/* Old format. */
		format = format.remove(QStringLiteral("%Y"))
		.remove(QStringLiteral("%M"))
		.remove(QStringLiteral("%D"))
		.remove(QStringLiteral("%h"))
		.remove(QStringLiteral("%m"));
	}

	/* Delivery time parameters. */
	if (!envelope.dmDeliveryTime().isNull()
	        && envelope.dmDeliveryTime().isValid()) {
		knowAtrrList.append(StringPairType(QStringLiteral("%<DY>"),
		    envelope.dmDeliveryTime().date().toString("yyyy")));
		knowAtrrList.append(StringPairType(QStringLiteral("%<Dy>"),
		    envelope.dmDeliveryTime().date().toString("yy")));
		knowAtrrList.append(StringPairType(QStringLiteral("%<DM>"),
		    envelope.dmDeliveryTime().date().toString("MM")));
		knowAtrrList.append(StringPairType(QStringLiteral("%<DD>"),
		    envelope.dmDeliveryTime().date().toString("dd")));
		knowAtrrList.append(StringPairType(QStringLiteral("%<Dh>"),
		    envelope.dmDeliveryTime().time().toString("hh")));
		knowAtrrList.append(StringPairType(QStringLiteral("%<Dm>"),
		    envelope.dmDeliveryTime().time().toString("mm")));
	} else {
		format = format.remove(QStringLiteral("%<DY>"))
		.remove(QStringLiteral("%<DM>"))
		.remove(QStringLiteral("%<DD>"))
		.remove(QStringLiteral("%<Dh>"))
		.remove(QStringLiteral("%<Dm>"));
	}

	/* Message envelope parameters. */
	knowAtrrList.append(StringPairType(QStringLiteral("%<EMID>"),
	    QString::number(dmId)));
	knowAtrrList.append(StringPairType(QStringLiteral("%<EMS>"),
	    replaceNameCharsAndTruncate(envelope.dmAnnotation())));

	/* Sender. */
	knowAtrrList.append(StringPairType(QStringLiteral("%<ESB>"),
	    envelope.dbIDSender()));
	knowAtrrList.append(StringPairType(QStringLiteral("%<ESN>"),
	    replaceNameCharsAndTruncate(envelope.dmSender())));
	knowAtrrList.append(StringPairType(QStringLiteral("%<ESA>"),
	    replaceNameCharsAndTruncate(envelope.dmSenderAddress())));

	/* Recipient. */
	knowAtrrList.append(StringPairType(QStringLiteral("%<ERB>"),
	    envelope.dbIDRecipient()));
	knowAtrrList.append(StringPairType(QStringLiteral("%<ERN>"),
	    replaceNameCharsAndTruncate(envelope.dmRecipient())));
	knowAtrrList.append(StringPairType(QStringLiteral("%<ERA>"),
	    replaceNameCharsAndTruncate(envelope.dmRecipientAddress())));

	/* These envelope parameters may be empty. */
	const QString na("NA");
	knowAtrrList.append(StringPairType(QStringLiteral("%<ESR>"),
	    (envelope.dmSenderRefNumber().isEmpty()) ? na :
	    replaceNameCharsAndTruncate(envelope.dmSenderRefNumber())));
	knowAtrrList.append(StringPairType(QStringLiteral("%<ESF>"),
	    (envelope.dmSenderIdent().isEmpty()) ? na :
	    replaceNameCharsAndTruncate(envelope.dmSenderIdent())));
	knowAtrrList.append(StringPairType(QStringLiteral("%<ERR>"),
	    (envelope.dmRecipientRefNumber().isEmpty()) ? na :
	    replaceNameCharsAndTruncate(envelope.dmRecipientRefNumber())));
	knowAtrrList.append(StringPairType(QStringLiteral("%<ERF>"),
	    (envelope.dmRecipientIdent().isEmpty()) ? na :
	    replaceNameCharsAndTruncate(envelope.dmRecipientIdent())));
	knowAtrrList.append(StringPairType(QStringLiteral("%<ETH>"),
	    (envelope.dmToHands().isEmpty()) ? na :
	    replaceNameCharsAndTruncate(envelope.dmToHands())));

	/* Message orientation. */
	knowAtrrList.append(StringPairType(QStringLiteral("%<MO>"),
	    dmTypePrefix));

	/* Attachment parameters. */
	knowAtrrList.append(StringPairType(QStringLiteral("%<FN>"),
	    attachName));

	/* Old version of message envelope parameters. */
	knowAtrrList.append(StringPairType(QStringLiteral("%n"),
	    replaceNameCharsAndTruncate(accountName)));
	knowAtrrList.append(StringPairType(QStringLiteral("%d"), dbId));
	knowAtrrList.append(StringPairType(QStringLiteral("%u"), userName));
	knowAtrrList.append(StringPairType(QStringLiteral("%i"),
	    QString::number(dmId)));
	knowAtrrList.append(StringPairType(QStringLiteral("%s"),
	    replaceNameCharsAndTruncate(envelope.dmAnnotation())));
	knowAtrrList.append(StringPairType(QStringLiteral("%O"),
	    envelope.dbIDSender()));
	knowAtrrList.append(StringPairType(QStringLiteral("%P"),
	    envelope.dbIDRecipient()));
	knowAtrrList.append(StringPairType(QStringLiteral("%S"),
	    replaceNameCharsAndTruncate(envelope.dmSender())));
	knowAtrrList.append(StringPairType(QStringLiteral("%R"),
	    replaceNameCharsAndTruncate(envelope.dmRecipient())));
	knowAtrrList.append(StringPairType(QStringLiteral("%f"), attachName));

	for (int i = 0; i < knowAtrrList.length(); ++i) {
		format.replace(knowAtrrList[i].first, knowAtrrList[i].second);
	}

	/* Treat backslashes as directory separators on all systems. */
	replaceBackslashes(format);
	replaceIllegalChars(format, prohibitDirSep);
	format = format.simplified();

	QString fileName = QDir::toNativeSeparators(format);

	/* Check filename length and truncate it on 255 chars. */
	if (QFileInfo(fileName).fileName().length() > FILE_NAME_MAX_LENGTH) {
		fileName = truncateFileName(fileName);
	}

	return fileName;
}
