/*
 * 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 "birbcount.h"

#include "birbstr.h"

/******************************************************************************
 * Callbacks
 *****************************************************************************/
static void
birb_count_list_model_items_changed_cb(G_GNUC_UNUSED GListModel *model,
                                       G_GNUC_UNUSED guint position,
                                       G_GNUC_UNUSED guint removed,
                                       G_GNUC_UNUSED guint added,
                                       gpointer data)
{
	guint *counter = data;

	*counter = *counter + 1;
}

static void
birb_count_property_changed_cb(G_GNUC_UNUSED GObject *self,
                               G_GNUC_UNUSED GParamSpec *pspec,
                               gpointer data)
{
	guint *counter = data;

	*counter = *counter + 1;
}

/******************************************************************************
 * Public API
 *****************************************************************************/
void
birb_count_list_model_items_changed(GListModel *model, guint *counter) {
	g_return_if_fail(G_IS_LIST_MODEL(model));
	g_return_if_fail(counter != NULL);

	g_signal_connect(model, "items-changed",
	                 G_CALLBACK(birb_count_list_model_items_changed_cb),
	                 counter);
}

void
birb_count_property_changed(GObject *obj, const char *name, guint *counter) {
	g_return_if_fail(G_IS_OBJECT(obj));
	g_return_if_fail(counter != NULL);

	if(birb_str_is_empty(name)) {
		g_signal_connect(obj,
		                 "notify",
		                 G_CALLBACK(birb_count_property_changed_cb),
		                 counter);
	} else {
		char *detailed_name = g_strdup_printf("notify::%s", name);

		g_signal_connect(obj,
		                 detailed_name,
		                 G_CALLBACK(birb_count_property_changed_cb),
		                 counter);

		g_free(detailed_name);
	}
}
