/*
 * Pidgin - Internet Messenger
 * Copyright (C) Pidgin Developers <devel@pidgin.im>
 *
 * Pidgin is the legal property of its developers, whose names are too numerous
 * to list here. Please refer to the COPYRIGHT file distributed with this
 * source distribution.
 *
 * 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 2 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 <https://www.gnu.org/licenses/>.
 */

#include <adwaita.h>

#include <birb.h>

#include <hsluv.h>

#include "pidgincolor.h"

/******************************************************************************
 * Public API
 *****************************************************************************/
float
pidgin_color_hue_for_text(const char *text) {
	GChecksum *checksum = NULL;
	guchar digest[20];
	gsize digest_len = sizeof(digest);

	checksum = g_checksum_new(G_CHECKSUM_SHA1);

	if(text != NULL) {
		g_checksum_update(checksum, (const guchar *)text, -1);
	}

	/* digest_len is an in-out parameter. */
	g_checksum_get_digest(checksum, digest, &digest_len);
	g_return_val_if_fail(digest_len > 2, 0);
	g_checksum_free(checksum);

	/* Calculate the hue based on the digest. We need a value between 0 and 1
	 * so we divide the value by 65535 which is the maximum value for 2 bytes.
	 *
	 * We treat this as a little endian int per XEP-0392
	 */
	return ((digest[1] << 8 | digest[0]) / 65535.0f) * 360.0f;
}

void
pidgin_color_calculate_for_text(const char *text, GdkRGBA *color) {
	GApplication *application = NULL;
	float hue = 0;
	double lightness = 40;
	double red = 0;
	double green = 0;
	double blue = 0;

	g_return_if_fail(color != NULL);

	application = g_application_get_default();
	if(ADW_IS_APPLICATION(application)) {
		AdwStyleManager *manager = NULL;

		manager = adw_application_get_style_manager(ADW_APPLICATION(application));
		if(adw_style_manager_get_dark(manager)) {
			lightness = 60;
		}
	}

	hue = pidgin_color_hue_for_text(text);

	/* If we're being called from unit test use the expected lightness. */
	if(g_test_initialized()) {
		lightness = 50;
	}

	hsluv2rgb(hue, 100, lightness, &red, &green, &blue);

	color->red = red;
	color->green = green;
	color->blue = blue;
	color->alpha = 1.0f;
}
