/*
 * 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 <QApplication> /* qApp */
#include <QFile>
#include <QFont>
#include <QString>

#include "src/datovka_shared/log/log.h"
#include "src/datovka_shared/settings/prefs.h"
#include "src/gui/styles.h"
#include "src/initialisation_gui.h"
#include "src/settings/prefs_specific.h"

/*!
 * @brief Get application style sheet text.
 *
 * @param[in] index Value as defined by enum PrefsSpecific::AppUiTheme.
 * @param[in] fontSizePt Font size in points.
 * @return Style sheet content.
 */
static
QString appUiStylesheet(const int index, const int fontSizePt)
{
	const QString styleSheetFilePath = GuiStyles::styleSheetPath(index);

	/* Set new font point size. */
	{
		QFont font = QApplication::font();
		font.setPointSize(fontSizePt);
		QApplication::setFont(font);
	}

	if (styleSheetFilePath.isEmpty()) {
		return QString();
	}

	QFile file(styleSheetFilePath);
	if (Q_UNLIKELY(!file.open(QFile::ReadOnly))) {
		logWarningNL(
		    "Couldn't open UI stylesheet file '%s'. Default theme is used.",
		    styleSheetFilePath.toUtf8().constData());
		return QString();
	}

	return GuiStyles::replaceStyleSheetVariables(
	    QLatin1String(file.readAll()), fontSizePt);
}

void loadAppUiThemeFromValues(const int index, const int fontScalePercent)
{
	static const QFont dfltFont = QApplication::font();

	int fontSizePt = dfltFont.pointSize();
	/* Only apply scaling factors in the range <0.8, 2.5>. */
	if ((fontScalePercent >= 80) && (fontScalePercent <= 250)) {
		fontSizePt = (fontSizePt * fontScalePercent) / 100;
	}

	QApplication *app = qApp;
	if (app != Q_NULLPTR) {
		app->setStyleSheet(appUiStylesheet(index, fontSizePt));
	}
}

void loadAppUiTheme(const Prefs &prefs)
{
	loadAppUiThemeFromValues(PrefsSpecific::appUiTheme(prefs),
	    PrefsSpecific::appUiThemeFontScalePercent(prefs)
	);
}
