/*
 * 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 <QtGlobal> /* QT_VERSION_CHECK */
#if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
#  include <QRandomGenerator>
#else /* < Qt-5.10.0 */
#  include <QDateTime>
#endif /* >= Qt-5.10.0 */

#include "src/datovka_shared/compat_qt/random.h"

void Compat::seedRand(void)
{
#if (QT_VERSION < QT_VERSION_CHECK(5, 10, 0))
	qsrand(
#if (QT_VERSION >= QT_VERSION_CHECK(5, 8, 0))
	    0xffffffff & QDateTime::currentDateTime().toSecsSinceEpoch()
#else /* < Qt-5.8 */
	    0xffffffff & (QDateTime::currentDateTime().toMSecsSinceEpoch() / 1000)
#endif /* >= Qt-5.8 */
	);
#endif /* < Qt-5.10.0 */
}

int Compat::randBounded(int upperBound)
{
#if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
	return QRandomGenerator::global()->bounded(upperBound);
#else /* < Qt-5.10.0 */
	return qrand() % upperBound;
#endif /* >= Qt-5.10.0 */
}

int Compat::randBoundedInterval(int lowerBound, int upperBound)
{
#if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
	return QRandomGenerator::global()->bounded(lowerBound, upperBound);
#else /* < Qt-5.10.0 */
	return (qrand() % (upperBound - lowerBound)) + lowerBound;
#endif /* >= Qt-5.10.0 */
}

void Compat::randFillRange(char *buffer, int size)
{
	if (Q_UNLIKELY((buffer == Q_NULLPTR) || (size <= 0))) {
		Q_ASSERT(0);
		return;
	}

#if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
	int count = size / sizeof(quint32);
	int remaining = size % sizeof(quint32);
	if (count > 0) {
		QRandomGenerator::global()->fillRange((quint32 *)buffer, count);
	}
	if (remaining > 0) {
		buffer += count * sizeof(quint32);
		for (int i = 0; i < remaining; ++i) {
			buffer[i] = QRandomGenerator::global()->bounded(256);
		}
	}
#else /* < Qt-5.10.0 */
	for (int i = 0; i < size; ++i) {
		buffer[i] = qrand() % 256;
	}
#endif /* >= Qt-5.10.0 */
}
