/*
 * Purple - Internet Messaging Library
 * Copyright (C) Pidgin Developers <devel@pidgin.im>
 *
 * Purple 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 library 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 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 General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this library; if not, see <https://www.gnu.org/licenses/>.
 */

#ifdef G_LOG_DOMAIN
# undef G_LOG_DOMAIN
#endif /* G_LOG_DOMAIN */
#define G_LOG_DOMAIN "PurplePresenceManager"

#include <glib/gi18n-lib.h>

#include <birb.h>

#include "purplepresencemanager.h"
#include "purplepresencemanagerprivate.h"

#include "purplecore.h"
#include "purpleui.h"

#define PURPLE_PRESENCE_MANAGER_SCHEMA_ID "im.pidgin.Purple.PresenceManager"
#define PURPLE_PRESENCE_MANAGER_DEFAULT_OFFLINE_ID "00000000-0000-0000-0000-000000000000"
#define PURPLE_PRESENCE_MANAGER_DEFAULT_AVAILABLE_ID "ffffffff-ffff-ffff-ffff-ffffffffffff"

enum {
	PROP_0,
	PROP_ACTIVE_INDEX,
	PROP_ACTIVE_PRESENCE,
	PROP_BACKEND,
	PROP_ITEM_TYPE,
	PROP_N_ITEMS,
	N_PROPERTIES,
};
static GParamSpec *properties[N_PROPERTIES] = {NULL, };

enum {
	SIG_ADDED,
	SIG_REMOVED,
	SIG_LOADED_FROM_BACKEND,
	N_SIGNALS,
};
static guint signals[N_SIGNALS] = {0, };

struct _PurplePresenceManager {
	GObject parent;

	PurplePresenceManagerBackend *backend;

	guint active_index;
	GPtrArray *presences;
};

/******************************************************************************
 * Helpers
 *****************************************************************************/
static void
purple_presence_manager_add_default_offline(PurplePresenceManager *manager) {
	PurpleSavedPresence *saved_presence = NULL;

	saved_presence = g_object_new(
		PURPLE_TYPE_SAVED_PRESENCE,
		"id", PURPLE_PRESENCE_MANAGER_DEFAULT_OFFLINE_ID,
		"name", _("Offline"),
		"primitive", PURPLE_PRESENCE_PRIMITIVE_OFFLINE,
		NULL);
	purple_presence_manager_add(manager, saved_presence);
	g_clear_object(&saved_presence);

	g_message("Added missing default offline saved presence.");
}

static void
purple_presence_manager_add_default_available(PurplePresenceManager *manager) {
	PurpleSavedPresence *saved_presence = NULL;

	saved_presence = g_object_new(
		PURPLE_TYPE_SAVED_PRESENCE,
		"id", PURPLE_PRESENCE_MANAGER_DEFAULT_AVAILABLE_ID,
		"name", _("Available"),
		"primitive", PURPLE_PRESENCE_PRIMITIVE_AVAILABLE,
		NULL);
	purple_presence_manager_add(manager, saved_presence);
	g_clear_object(&saved_presence);

	g_message("Added missing default available saved presence.");
}

static void
purple_presence_manager_set_backend(PurplePresenceManager *manager,
                                    PurplePresenceManagerBackend *backend)
{
	g_return_if_fail(PURPLE_IS_PRESENCE_MANAGER(manager));

	if(g_set_object(&manager->backend, backend)) {
		g_object_notify_by_pspec(G_OBJECT(manager), properties[PROP_BACKEND]);
	}

	if(!PURPLE_IS_PRESENCE_MANAGER_BACKEND(manager->backend)) {
		purple_presence_manager_add_default_offline(manager);
		purple_presence_manager_add_default_available(manager);
	}
}

static gboolean
purple_presence_manager_get_active_index_mapping(GValue *value,
                                                 GVariant *variant,
                                                 gpointer data)
{
	PurplePresenceManager *manager = data;
	PurpleSavedPresence *presence = NULL;
	const char *id = NULL;
	guint index = 0;

	/* Get the id of the saved presence from gsettings. */
	id = g_variant_get_string(variant, NULL);

	presence = purple_presence_manager_find_with_id(manager, id, &index);
	if(PURPLE_IS_SAVED_PRESENCE(presence)) {
		g_value_set_uint(value, index);

		return TRUE;
	}

	return FALSE;
}

static GVariant *
purple_presence_manager_set_active_index_mapping(const GValue *value,
                                                 const GVariantType *expected_type,
                                                 gpointer data)
{
	PurplePresenceManager *manager = data;
	guint index = 0;

	if(!g_variant_type_equal(expected_type, G_VARIANT_TYPE_STRING)) {
		return NULL;
	}

	index = g_value_get_uint(value);
	if(index < manager->presences->len) {
		PurpleSavedPresence *presence = NULL;
		const char *id = NULL;

		presence = g_ptr_array_index(manager->presences, index);
		id = purple_saved_presence_get_id(presence);

		return g_variant_new_string(id);
	}

	return NULL;
}

/******************************************************************************
 * Callbacks
 *****************************************************************************/
static void
purple_presence_manager_backend_load_saved_presences_cb(GObject *source,
                                                        GAsyncResult *result,
                                                        gpointer data)
{
	PurpleCore *core = NULL;
	PurplePresenceManager *manager = data;
	PurplePresenceManagerBackend *backend = NULL;
	GError *error = NULL;
	GListModel *presences = NULL;
	GSettings *settings = NULL;
	guint n_items = 0;
	gboolean offline_found = FALSE;
	gboolean available_found = FALSE;

	backend = PURPLE_PRESENCE_MANAGER_BACKEND(source);
	presences = purple_presence_manager_backend_load_saved_presences_finish(backend,
	                                                                        result,
	                                                                        &error);

	if(error != NULL) {
		g_warning("failed to load saved presences from backend %s: %s",
		          G_OBJECT_TYPE_NAME(source),
		          error->message);
		g_clear_error(&error);
		g_clear_object(&presences);

		return;
	}

	if(!G_LIST_MODEL(presences)) {
		g_warning("the %s backend did not return a list of saved presences",
		          G_OBJECT_TYPE_NAME(source));

		g_clear_object(&presences);

		return;
	}

	n_items = g_list_model_get_n_items(presences);
	for(guint i = 0; i < n_items; i++) {
		PurpleSavedPresence *saved_presence = NULL;
		const char *id = NULL;

		saved_presence = g_list_model_get_item(presences, i);
		purple_presence_manager_add(manager, saved_presence);

		id = purple_saved_presence_get_id(saved_presence);

		if(!offline_found &&
		   birb_str_equal(id, PURPLE_PRESENCE_MANAGER_DEFAULT_OFFLINE_ID))
		{
			offline_found = TRUE;
		}

		if(!available_found &&
		   birb_str_equal(id, PURPLE_PRESENCE_MANAGER_DEFAULT_AVAILABLE_ID))
		{
			available_found = TRUE;
		}

		g_clear_object(&saved_presence);
	}

	g_message("loaded %u saved presences", n_items);

	/* Now make sure we have our default offline and available tasks and if not
	 * create them.
	 */
	if(!offline_found) {
		purple_presence_manager_add_default_offline(manager);
	}

	if(!available_found) {
		purple_presence_manager_add_default_available(manager);
	}

	/* With everything loaded, bind the active id to the settings. */
	core = purple_core_get_default();
	settings = purple_core_new_settings(core,
	                                    PURPLE_PRESENCE_MANAGER_SCHEMA_ID);
	g_settings_bind_with_mapping(settings, "active", manager,
	                             "active-index", G_SETTINGS_BIND_DEFAULT,
	                             purple_presence_manager_get_active_index_mapping,
	                             purple_presence_manager_set_active_index_mapping,
	                             manager, NULL);
	g_clear_object(&settings);

	/* Emit the loaded from backend signal. */
	g_signal_emit(manager, signals[SIG_LOADED_FROM_BACKEND], 0, NULL);
}

static void
purple_presence_manager_save_saved_presence_cb(GObject *source,
                                               GAsyncResult *result,
                                               G_GNUC_UNUSED gpointer data)
{
	PurplePresenceManagerBackend *backend = NULL;
	GError *error = NULL;
	gboolean success = FALSE;

	backend = PURPLE_PRESENCE_MANAGER_BACKEND(source);
	success = purple_presence_manager_backend_save_saved_presence_finish(backend,
	                                                                     result,
	                                                                     &error);

	if(!success) {
		const char *message = "unknown error";

		if(error != NULL) {
			message = error->message;
		}

		g_warning("failed to save saved presence: %s", message);

		g_clear_error(&error);
	}
}

/******************************************************************************
 * GListModel Implementation
 *****************************************************************************/
static GType
purple_presence_manager_get_item_type(G_GNUC_UNUSED GListModel *list) {
	return PURPLE_TYPE_SAVED_PRESENCE;
}

static guint
purple_presence_manager_get_n_items(GListModel *list) {
	PurplePresenceManager *manager = PURPLE_PRESENCE_MANAGER(list);

	return manager->presences->len;
}

static gpointer
purple_presence_manager_get_item(GListModel *list, guint position) {
	PurplePresenceManager *manager = PURPLE_PRESENCE_MANAGER(list);
	PurpleSavedPresence *presence = NULL;

	if(position < manager->presences->len) {
		presence = g_ptr_array_index(manager->presences, position);
		g_object_ref(presence);
	}

	return presence;
}

static void
purple_presence_manager_list_model_init(GListModelInterface *iface) {
	iface->get_item_type = purple_presence_manager_get_item_type;
	iface->get_n_items = purple_presence_manager_get_n_items;
	iface->get_item = purple_presence_manager_get_item;
}

/******************************************************************************
 * GObject Implementation
 *****************************************************************************/
G_DEFINE_FINAL_TYPE_WITH_CODE(PurplePresenceManager, purple_presence_manager,
                              G_TYPE_OBJECT,
                              G_IMPLEMENT_INTERFACE(G_TYPE_LIST_MODEL,
                                                    purple_presence_manager_list_model_init))

static void
purple_presence_manager_finalize(GObject *obj) {
	PurplePresenceManager *manager = PURPLE_PRESENCE_MANAGER(obj);

	g_clear_object(&manager->backend);
	g_clear_pointer(&manager->presences, g_ptr_array_unref);

	G_OBJECT_CLASS(purple_presence_manager_parent_class)->finalize(obj);
}

static void
purple_presence_manager_get_property(GObject *obj, guint param_id,
                                     GValue *value, GParamSpec *pspec)
{
	PurplePresenceManager *manager = PURPLE_PRESENCE_MANAGER(obj);

	switch(param_id) {
	case PROP_ACTIVE_INDEX:
		g_value_set_uint(value,
		                 purple_presence_manager_get_active_index(manager));
		break;
	case PROP_ACTIVE_PRESENCE:
		g_value_set_object(value, purple_presence_manager_get_active(manager));
		break;
	case PROP_BACKEND:
		g_value_set_object(value,
		                   purple_presence_manager_get_backend(manager));
		break;
	case PROP_ITEM_TYPE:
		g_value_set_gtype(value,
		                  purple_presence_manager_get_item_type(G_LIST_MODEL(manager)));
		break;
	case PROP_N_ITEMS:
		g_value_set_uint(value,
		                 purple_presence_manager_get_n_items(G_LIST_MODEL(manager)));
		break;
	default:
		G_OBJECT_WARN_INVALID_PROPERTY_ID(obj, param_id, pspec);
		break;
	}
}

static void
purple_presence_manager_set_property(GObject *obj, guint param_id,
                                     const GValue *value, GParamSpec *pspec)
{
	PurplePresenceManager *manager = PURPLE_PRESENCE_MANAGER(obj);

	switch(param_id) {
	case PROP_ACTIVE_INDEX:
		purple_presence_manager_set_active_from_index(manager,
		                                              g_value_get_uint(value));
		break;
	case PROP_BACKEND:
		purple_presence_manager_set_backend(manager,
		                                    g_value_get_object(value));
		break;
	default:
		G_OBJECT_WARN_INVALID_PROPERTY_ID(obj, param_id, pspec);
		break;
	}
}

static void
purple_presence_manager_init(PurplePresenceManager *manager) {
	manager->presences = g_ptr_array_new_full(0,
	                                          (GDestroyNotify)g_object_unref);
	manager->active_index = G_MAXUINT;
}

static void
purple_presence_manager_class_init(PurplePresenceManagerClass *klass) {
	GObjectClass *obj_class = G_OBJECT_CLASS(klass);

	obj_class->finalize = purple_presence_manager_finalize;
	obj_class->get_property = purple_presence_manager_get_property;
	obj_class->set_property = purple_presence_manager_set_property;

	/**
	 * PurplePresenceManager:active-index:
	 *
	 * The index of the active saved presence.
	 *
	 * Since: 3.0
	 */
	properties[PROP_ACTIVE_INDEX] = g_param_spec_uint(
		"active-index", NULL, NULL,
		0, G_MAXUINT, 0,
		G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | G_PARAM_EXPLICIT_NOTIFY);

	/**
	 * PurplePresenceManager:active-presence:
	 *
	 * The [class@SavedPresence] that is currently active.
	 *
	 * Since: 3.0
	 */
	properties[PROP_ACTIVE_PRESENCE] = g_param_spec_object(
		"active-presence", NULL, NULL,
		PURPLE_TYPE_SAVED_PRESENCE,
		G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);

	/**
	 * PurplePresenceManager:backend:
	 *
	 * The [class@PurplePresenceManagerBackend] that is being used.
	 *
	 * Since: 3.0
	 */
	properties[PROP_BACKEND] = g_param_spec_object(
		"backend", NULL, NULL,
		PURPLE_TYPE_PRESENCE_MANAGER_BACKEND,
		G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS |
		G_PARAM_EXPLICIT_NOTIFY);

	/**
	 * PurplePresenceManager:item-type:
	 *
	 * The type of items. See [vfunc@Gio.ListModel.get_item_type].
	 *
	 * Since: 3.0
	 */
	properties[PROP_ITEM_TYPE] = g_param_spec_gtype(
		"item-type", NULL, NULL,
		G_TYPE_OBJECT,
		G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);

	/**
	 * PurplePresenceManager:n-items:
	 *
	 * The number of items. See [vfunc@Gio.ListModel.get_n_items].
	 *
	 * Since: 3.0
	 */
	properties[PROP_N_ITEMS] = g_param_spec_uint(
		"n-items", NULL, NULL,
		0, G_MAXUINT, 0,
		G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);

	g_object_class_install_properties(obj_class, N_PROPERTIES, properties);

	/**
	 * PurplePresenceManager::added:
	 * @self: The instance.
	 * @presence: The presence that was added.
	 *
	 * Emitted when a [class@SavedPresence] is successfully added to the
	 * manager.
	 *
	 * Since: 3.0
	 */
	signals[SIG_ADDED] = g_signal_new_class_handler(
		"added",
		G_OBJECT_CLASS_TYPE(klass),
		G_SIGNAL_RUN_LAST,
		NULL,
		NULL,
		NULL,
		NULL,
		G_TYPE_NONE,
		1,
		PURPLE_TYPE_SAVED_PRESENCE);

	/**
	 * PurplePresenceManager::removed:
	 * @self: The instance.
	 * @presence: The presence that was removed.
	 *
	 * Emitted when a [class@SavedPresence] is successfully removed from the
	 * manager.
	 *
	 * Since: 3.0
	 */
	signals[SIG_REMOVED] = g_signal_new_class_handler(
		"removed",
		G_OBJECT_CLASS_TYPE(klass),
		G_SIGNAL_RUN_LAST,
		NULL,
		NULL,
		NULL,
		NULL,
		G_TYPE_NONE,
		1,
		PURPLE_TYPE_SAVED_PRESENCE);

	/**
	 * PurplePresenceManager::loaded-from-backend:
	 * @manager: the instance
	 * @error: (nullable): the error if one was encountered
	 *
	 * This signal is emitted after accounts have been loaded from the backend.
	 *
	 * This will still be emitted if there is no backend.
	 *
	 * Since: 3.0
	 */
	signals[SIG_LOADED_FROM_BACKEND] = g_signal_new_class_handler(
		"loaded-from-backend",
		G_OBJECT_CLASS_TYPE(klass),
		G_SIGNAL_RUN_LAST,
		NULL,
		NULL,
		NULL,
		NULL,
		G_TYPE_NONE,
		1,
		G_TYPE_ERROR);
}

/******************************************************************************
 * Private API
 *****************************************************************************/
PurplePresenceManager *
purple_presence_manager_startup(PurpleCore *core, GError **error) {
	PurplePresenceManager *manager = NULL;
	PurplePresenceManagerBackend *backend = NULL;
	PurpleUi *ui = NULL;
	GError *local_error = NULL;

	ui = purple_core_get_ui(core);
	backend = purple_ui_get_presence_manager_backend(ui, &local_error);
	if(local_error != NULL) {
		g_propagate_error(error, local_error);

		return NULL;
	}

	manager = g_object_new(
		PURPLE_TYPE_PRESENCE_MANAGER,
		"backend", backend,
		NULL);

	g_clear_object(&backend);

	return manager;
}

void
purple_presence_manager_load_from_backend(PurplePresenceManager *manager) {
	g_return_if_fail(PURPLE_IS_PRESENCE_MANAGER(manager));

	if(PURPLE_IS_PRESENCE_MANAGER_BACKEND(manager->backend)) {
		purple_presence_manager_backend_load_saved_presences_async(manager->backend,
		                                                           NULL,
		                                                           purple_presence_manager_backend_load_saved_presences_cb,
		                                                           manager);
	} else {
		g_signal_emit(manager, signals[SIG_LOADED_FROM_BACKEND], 0, NULL);
	}
}

/******************************************************************************
 * Public API
 *****************************************************************************/
gboolean
purple_presence_manager_add(PurplePresenceManager *manager,
                            PurpleSavedPresence *saved_presence)
{
	PurpleSavedPresence *existing = NULL;
	const char *id = NULL;
	guint position = 0;

	g_return_val_if_fail(PURPLE_IS_PRESENCE_MANAGER(manager), FALSE);
	g_return_val_if_fail(PURPLE_IS_SAVED_PRESENCE(saved_presence), FALSE);

	id = purple_saved_presence_get_id(saved_presence);
	existing = purple_presence_manager_find_with_id(manager, id, NULL);
	if(PURPLE_IS_SAVED_PRESENCE(existing)) {
		return FALSE;
	}

	position = manager->presences->len;
	g_ptr_array_add(manager->presences, g_object_ref(saved_presence));

	if(PURPLE_IS_PRESENCE_MANAGER_BACKEND(manager->backend)) {
		purple_presence_manager_backend_save_saved_presence_async(manager->backend,
		                                                          saved_presence,
		                                                          NULL,
		                                                          purple_presence_manager_save_saved_presence_cb,
		                                                          manager);
	}

	g_list_model_items_changed(G_LIST_MODEL(manager), position, 0, 1);
	g_signal_emit(manager, signals[SIG_ADDED], 0, saved_presence);

	return TRUE;
}

PurpleSavedPresence *
purple_presence_manager_find_with_id(PurplePresenceManager *manager,
                                     const char *id,
                                     guint *position)
{
	g_return_val_if_fail(PURPLE_IS_PRESENCE_MANAGER(manager), NULL);
	g_return_val_if_fail(!birb_str_is_empty(id), NULL);

	for(guint i = 0; i < manager->presences->len; i++) {
		PurpleSavedPresence *presence = NULL;
		const char *presence_id = NULL;

		presence = g_ptr_array_index(manager->presences, i);
		presence_id = purple_saved_presence_get_id(presence);

		if(birb_str_equal(presence_id, id)) {
			if(position != NULL) {
				*position = i;
			}

			return presence;
		}
	}

	return NULL;
}

PurpleSavedPresence *
purple_presence_manager_get_active(PurplePresenceManager *manager) {
	g_return_val_if_fail(PURPLE_IS_PRESENCE_MANAGER(manager), NULL);

	if(manager->presences->len == 0) {
		return NULL;
	}

	g_return_val_if_fail(manager->active_index < manager->presences->len,
	                     NULL);

	return g_ptr_array_index(manager->presences, manager->active_index);
}

guint
purple_presence_manager_get_active_index(PurplePresenceManager *manager) {
	g_return_val_if_fail(PURPLE_IS_PRESENCE_MANAGER(manager), G_MAXUINT);

	return manager->active_index;
}

PurplePresenceManagerBackend *
purple_presence_manager_get_backend(PurplePresenceManager *manager) {
	g_return_val_if_fail(PURPLE_IS_PRESENCE_MANAGER(manager), NULL);

	return manager->backend;
}

PurplePresenceManager *
purple_presence_manager_get_default(void) {
	return purple_core_get_presence_manager(purple_core_get_default());
}

GListModel *
purple_presence_manager_get_default_as_model(void) {
	PurplePresenceManager *manager = NULL;

	manager = purple_core_get_presence_manager(purple_core_get_default());
	if(PURPLE_IS_PRESENCE_MANAGER(manager)) {
		return G_LIST_MODEL(manager);
	}

	return NULL;
}

void
purple_presence_manager_set_active_from_index(PurplePresenceManager *manager,
                                              guint index)
{
	g_return_if_fail(PURPLE_IS_PRESENCE_MANAGER(manager));

	if(index < manager->presences->len && index != manager->active_index) {
		GObject *obj = G_OBJECT(manager);
		manager->active_index = index;

		g_object_freeze_notify(obj);
		g_object_notify_by_pspec(obj, properties[PROP_ACTIVE_PRESENCE]);
		g_object_notify_by_pspec(obj, properties[PROP_ACTIVE_INDEX]);
		g_object_thaw_notify(obj);
	}
}

gboolean
purple_presence_manager_set_active_from_id(PurplePresenceManager *manager,
                                           const char *id)
{
	PurpleSavedPresence *presence = NULL;
	guint index = 0;

	g_return_val_if_fail(PURPLE_IS_PRESENCE_MANAGER(manager), FALSE);
	g_return_val_if_fail(!birb_str_is_empty(id), FALSE);

	presence = purple_presence_manager_find_with_id(manager, id, &index);
	if(PURPLE_IS_SAVED_PRESENCE(presence)) {
		purple_presence_manager_set_active_from_index(manager, index);

		return TRUE;
	}

	return FALSE;
}

gboolean
purple_presence_manager_remove(PurplePresenceManager *manager, const char *id)
{
	PurpleSavedPresence *presence = NULL;
	guint index;

	g_return_val_if_fail(PURPLE_IS_PRESENCE_MANAGER(manager), FALSE);
	g_return_val_if_fail(!birb_str_is_empty(id), FALSE);

	presence = purple_presence_manager_find_with_id(manager, id, &index);
	if(!PURPLE_IS_SAVED_PRESENCE(presence)) {
		return FALSE;
	}

	presence = g_ptr_array_steal_index(manager->presences, index);

	g_signal_emit(manager, signals[SIG_REMOVED], 0, presence);
	g_list_model_items_changed(G_LIST_MODEL(manager), index, 1, 0);
	g_object_notify_by_pspec(G_OBJECT(manager), properties[PROP_N_ITEMS]);

	/* Unref the presence as we are now done with it. */
	g_object_unref(presence);

	return TRUE;
}
