/*
 * 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 "src/models/helper.h"

/*
 * Specifies number of bits to be used for message id when combining with other
 * data.
 */
#define MSG_ID_WIDTH 48

/* Invalid is the latest. */
static
const QString dateTimeSortFormat("0yyyyMMddHHmmsszzz"); /* 18 digits */
static
const QString invalidTimeSortValue("100000000000000000"); /* 18 digits */

qint64 ModelHelper::sortRank(qint16 num, qint64 dmId)
{
	qint64 id = num;
	id = id << MSG_ID_WIDTH;
	id += dmId;
	return id;
}

QString ModelHelper::sortRank(const QString &hiStr, qint64 dmId)
{
	return QStringLiteral("%1%2").arg(hiStr).arg(dmId, 20, 10, QChar('0'));
}

QString ModelHelper::sortRank(const QString &hiStr, const QString &loStr)
{
	return hiStr + loStr;
}

QString ModelHelper::sortRank(const QDateTime &hiDateTime, qint64 loDmId)
{
	if (hiDateTime.isValid()) {
		return QStringLiteral("%1%2")
		    .arg(hiDateTime.toUTC().toString(dateTimeSortFormat))
		    .arg(loDmId, 20, 10, QChar('0'));
	} else {
		return QStringLiteral("%1%2")
		    .arg(invalidTimeSortValue)
		    .arg(loDmId, 20, 10, QChar('0'));
	}
}
