#include <gio/gio.h>
#include <cstring>
#include <string_view>

namespace glib {

bool IsInDarkTheme() {
	bool success = false;

	GSettings* settings = ::g_settings_new("org.gnome.desktop.interface");
	if (!settings)
		return false;

	GVariant* val = ::g_settings_get_value(settings, "color-scheme");
	if (!val)
		return false;

	const gchar* str;
	::g_variant_get(val, "&s", &str); /* should not be freed */
	if (!str) /* how */
		return false;

	success |= !std::strcmp(str, "prefer-dark");

	::g_variant_unref(val);

	if (success) {
		::g_object_unref(settings);
		return success;
	}

	GVariant* gtk_theme = ::g_settings_get_value(settings, "gtk-theme");
	if (!gtk_theme)
		return false;

	const gchar* gtk_theme_str;
	::g_variant_get(gtk_theme, "&s", gtk_theme_str);
	if (!gtk_theme_str)
		return false;

	static constexpr std::string_view suffix = "-dark";

	size_t gtk_theme_len = strlen(gtk_theme_str);

	success |= !std::strncmp(gtk_theme_str + gtk_theme_len - suffix.length(), suffix.data(), suffix.length());

	::g_object_unref(settings);
	return success;
}

}
