/*
 * 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 "src/datovka_shared/compat_qt/random.h"
#include "src/datovka_shared/utility/strings.h"

QString Utility::generateRandomString(int length)
{
	static const QString possibleCharacters(
	    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
	    "abcdefghijklmnopqrstuvwxyz"
	    "0123456789"
	    "!#$%&()*+,-.:=?@[]_{|}~");

	QString randomString;

	for (int i = 0; i < length; ++i) {
		int index = Compat::randBounded(possibleCharacters.length());
		QChar nextChar = possibleCharacters.at(index);
		randomString.append(nextChar);
	}
	return randomString;
}

#define KILOBYTE Q_INT64_C(1024)
#define MEGABYTE Q_INT64_C(1048576)
#define GIGABYTE Q_INT64_C(1073741824)
#define TERABYTE Q_INT64_C(1099511627776)

/*!
 * @brief Compute approximate size string including units.
 *
 * @param[in] size Size in bytes.
 * @return String with unit.
 */
QString Utility::sizeString(qint64 size)
{
	if (Q_UNLIKELY(size < 0)) {
		return tr("unknown");
	} else if (size > TERABYTE) {
		return QString::number(size / TERABYTE) + QStringLiteral(" TB");
	} else if (size > GIGABYTE) {
		return QString::number(size / GIGABYTE) + QStringLiteral(" GB");
	} else if (size > MEGABYTE) {
		return QString::number(size / MEGABYTE) + QStringLiteral(" MB");
	} else if (size > KILOBYTE) {
		return QString::number(size / KILOBYTE) + QStringLiteral(" kB");
	} else {
		return QString::number(size) + QStringLiteral(" B");
	}
}
