/*
 * Copyright (C) Birb Developers
 *
 * Birb is the legal property of its developers, whose names are too numerous
 * to list here. Please refer to the AUTHORS file distributed with this source
 * distribution
 *
 * This library is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by the
 * Free Software Foundation; either version 2.1 of the License, or (at your
 * option) any later version.
 *
 * This library 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 Lesser General Public License
 * for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this library; if not, see <https://www.gnu.org/licenses/>.
 */

#include "birbutf8.h"

/******************************************************************************
 * Public API
 *****************************************************************************/
gboolean
birb_utf8_equal(const char *str1, const char *str2) {
	return birb_utf8_compare(str1, str2) == 0;
}

int
birb_utf8_compare(const char *str1, const char *str2) {
	char *folded1 = NULL;
	char *folded2 = NULL;
	char *normalized1 = NULL;
	char *normalized2 = NULL;
	int ret = 0;

	/* Do the basic pointer checks. */
	if(str1 == str2) {
		return 0;
	} else if(str1 != NULL && str2 == NULL) {
		return -1;
	} else if(str1 == NULL && str2 != NULL) {
		return 1;
	}

	/* g_utf8_ normalize returns null if the string is not valid UTF8. We use
	 * this to skip calling g_utf8_validate and it lets us do simple pointer
	 * checks again. We use G_NORMALIZE_NFKC as it's the name mentioned in
	 * Stringprep and other documentation.
	 */
	normalized1 = g_utf8_normalize(str1, -1, G_NORMALIZE_NFKC);
	normalized2 = g_utf8_normalize(str2, -1, G_NORMALIZE_NFKC);

	if(normalized1 == normalized2) {
		/* These shouldn't ever be the same non-null pointer, so we're just
		 * being defensive here.
		 */
		g_clear_pointer(&normalized1, g_free);
		g_clear_pointer(&normalized2, g_free);

		return 0;
	} else if(normalized1 != NULL && normalized2 == NULL) {
		g_clear_pointer(&normalized1, g_free);

		return -1;
	} else if(normalized1 == NULL && normalized2 != NULL) {
		g_clear_pointer(&normalized2, g_free);

		return 1;
	}

	/* Now case fold the normalized strings. */
	folded1 = g_utf8_casefold(normalized1, -1);
	g_clear_pointer(&normalized1, g_free);

	folded2 = g_utf8_casefold(normalized2, -1);
	g_clear_pointer(&normalized2, g_free);

	/* I should be able to listen to the radio while I'm collating. */
	ret = g_utf8_collate(folded1, folded2);

	g_clear_pointer(&folded1, g_free);
	g_clear_pointer(&folded2, g_free);

	return ret;
}
