/*
 * 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/>.
 */

#include "purpleconversationmanager.h"
#include "purpleconversationmanagerprivate.h"

#include "core.h"
#include "purplecontact.h"
#include "purpleui.h"
#include "util.h"

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

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

struct _PurpleConversationManager {
	GObject parent;

	char *filename;

	GPtrArray *conversations;
};

static PurpleConversationManager *default_manager = NULL;

typedef gboolean (*PurpleConversationManagerCompareFunc)(PurpleConversation *conversation, gpointer userdata);

/******************************************************************************
 * Helpers
 *****************************************************************************/
static void
purple_conversation_manager_set_filename(PurpleConversationManager *manager,
                                         const char *filename)
{
	g_return_if_fail(PURPLE_IS_CONVERSATION_MANAGER(manager));

	if(g_set_str(&manager->filename, filename)) {
		g_object_notify_by_pspec(G_OBJECT(manager), properties[PROP_FILENAME]);
	}
}

/******************************************************************************
 * Callbacks
 *****************************************************************************/
static void
purple_conversation_manager_conversation_changed_cb(GObject *source,
                                                    GParamSpec *pspec,
                                                    gpointer data)
{
	g_signal_emit(data, signals[SIG_CONVERSATION_CHANGED],
	              g_param_spec_get_name_quark(pspec),
	              source, pspec);
}

static void
purple_conversation_manager_present_conversation_cb(PurpleConversation *conversation,
                                                    gpointer data)
{
	g_signal_emit(data, signals[SIG_PRESENT_CONVERSATION], 0, conversation);
}

/******************************************************************************
 * GListModel Implementation
 *****************************************************************************/
static GType
purple_conversation_manager_get_item_type(G_GNUC_UNUSED GListModel *list) {
	return PURPLE_TYPE_CONVERSATION;
}

static guint
purple_conversation_manager_get_n_items(GListModel *list) {
	PurpleConversationManager *manager = PURPLE_CONVERSATION_MANAGER(list);

	return manager->conversations->len;
}

static gpointer
purple_conversation_manager_get_item(GListModel *list, guint position) {
	PurpleConversationManager *manager = PURPLE_CONVERSATION_MANAGER(list);
	PurpleConversation *conversation = NULL;

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

	return conversation;
}

static void
pidgin_conversation_manager_list_model_iface_init(GListModelInterface *iface) {
	iface->get_item_type = purple_conversation_manager_get_item_type;
	iface->get_n_items = purple_conversation_manager_get_n_items;
	iface->get_item = purple_conversation_manager_get_item;
}

/******************************************************************************
 * GObject Implementation
 *****************************************************************************/
G_DEFINE_FINAL_TYPE_WITH_CODE(PurpleConversationManager,
                              purple_conversation_manager,
                              G_TYPE_OBJECT,
                              G_IMPLEMENT_INTERFACE(G_TYPE_LIST_MODEL,
                                                    pidgin_conversation_manager_list_model_iface_init))

/******************************************************************************
 * GObject Implementation
 *****************************************************************************/
static void
purple_conversation_manager_init(PurpleConversationManager *manager) {
	manager->conversations = g_ptr_array_new_full(10, g_object_unref);
}

static void
purple_conversation_manager_finalize(GObject *obj) {
	PurpleConversationManager *manager = PURPLE_CONVERSATION_MANAGER(obj);

	g_clear_pointer(&manager->conversations, g_ptr_array_unref);
	g_clear_pointer(&manager->filename, g_free);

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

static void
purple_conversation_manager_get_property(GObject *obj, guint param_id,
                                         GValue *value, GParamSpec *pspec)
{
	PurpleConversationManager *manager = PURPLE_CONVERSATION_MANAGER(obj);

	switch(param_id) {
	case PROP_FILENAME:
		g_value_set_string(value,
		                   purple_conversation_manager_get_filename(manager));
		break;
	case PROP_ITEM_TYPE:
		g_value_set_gtype(value,
		                  purple_conversation_manager_get_item_type(G_LIST_MODEL(manager)));
		break;
	case PROP_N_ITEMS:
		g_value_set_uint(value,
		                 purple_conversation_manager_get_n_items(G_LIST_MODEL(manager)));
		break;
	default:
		G_OBJECT_WARN_INVALID_PROPERTY_ID(obj, param_id, pspec);
		break;
	}
}

static void
purple_conversation_manager_set_property(GObject *obj, guint param_id,
                                         const GValue *value,
                                         GParamSpec *pspec)
{
	PurpleConversationManager *manager = PURPLE_CONVERSATION_MANAGER(obj);

	switch(param_id) {
	case PROP_FILENAME:
		purple_conversation_manager_set_filename(manager,
		                                         g_value_get_string(value));
		break;
	default:
		G_OBJECT_WARN_INVALID_PROPERTY_ID(obj, param_id, pspec);
		break;
	}
}

static void
purple_conversation_manager_class_init(PurpleConversationManagerClass *klass) {
	GObjectClass *obj_class = G_OBJECT_CLASS(klass);

	obj_class->finalize = purple_conversation_manager_finalize;
	obj_class->get_property = purple_conversation_manager_get_property;
	obj_class->set_property = purple_conversation_manager_set_property;

	/**
	 * PurpleConversationManager:filename:
	 *
	 * The filename that the manager should save its contents to.
	 *
	 * If this is %NULL, no serialization will be performed.
	 *
	 * Since: 3.0
	 */
	properties[PROP_FILENAME] = g_param_spec_string(
		"filename", NULL, NULL,
		NULL,
		G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS);

	/**
	 * PurpleConversationManager: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);

	/**
	 * PurpleConversationManager: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);

	/**
	 * PurpleConversationManager::added:
	 * @manager: The manager.
	 * @conversation: The conversation that was added.
	 *
	 * Emitted after @conversation has been added to @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_CONVERSATION);

	/**
	 * PurpleConversationManager::removed:
	 * @manager: The manager.
	 * @conversation: The conversation that was removed.
	 *
	 * Emitted after @conversation has been removed from @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_CONVERSATION);

	/**
	 * PurpleConversationManager::conversation-changed:
	 * @manager: The account manager instance.
	 * @conversation: The conversation that was changed.
	 * @pspec: The [class@GObject.ParamSpec] for the property that changed.
	 *
	 * This is a propagation of the notify signal from @conversation. This
	 * means that your callback will be called for any conversation that
	 * @manager knows about.
	 *
	 * This also supports details, so you can specify the signal name as
	 * something like `conversation-changed::title` and your callback will only
	 * be called when [property@Conversation:title] has been changed.
	 *
	 * Since: 3.0
	 */
	signals[SIG_CONVERSATION_CHANGED] = g_signal_new_class_handler(
		"conversation-changed",
		G_OBJECT_CLASS_TYPE(klass),
		G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED,
		NULL,
		NULL,
		NULL,
		NULL,
		G_TYPE_NONE,
		2,
		PURPLE_TYPE_CONVERSATION,
		G_TYPE_PARAM);

	/**
	 * PurpleConversationManager::present-conversation:
	 * @manager: The instance.
	 * @conversation: The conversation that should be presented.
	 *
	 * This is a propagation of [signal@Conversation::present]. This means that
	 * your callback will be called for any conversation that @manager knows
	 * about.
	 *
	 * Since: 3.0
	 */
	signals[SIG_PRESENT_CONVERSATION] = g_signal_new_class_handler(
		"present-conversation",
		G_OBJECT_CLASS_TYPE(klass),
		G_SIGNAL_RUN_LAST,
		NULL,
		NULL,
		NULL,
		NULL,
		G_TYPE_NONE,
		1,
		PURPLE_TYPE_CONVERSATION);
}

/******************************************************************************
 * Private API
 *****************************************************************************/
void
purple_conversation_manager_startup(void) {
	if(default_manager == NULL) {
		PurpleUi *ui = purple_core_get_ui();

		default_manager = purple_ui_get_conversation_manager(ui);
		if(PURPLE_IS_CONVERSATION_MANAGER(default_manager)) {
			g_object_add_weak_pointer(G_OBJECT(default_manager),
			                          (gpointer *)&default_manager);
		}
	}
}

void
purple_conversation_manager_shutdown(void) {
	g_clear_object(&default_manager);
}

/******************************************************************************
 * Public API
 *****************************************************************************/
gboolean
purple_conversation_manager_add(PurpleConversationManager *manager,
                                PurpleConversation *conversation)
{
	guint position = 0;

	g_return_val_if_fail(PURPLE_IS_CONVERSATION_MANAGER(manager), FALSE);
	g_return_val_if_fail(PURPLE_IS_CONVERSATION(conversation), FALSE);

	if(g_ptr_array_find(manager->conversations, conversation, NULL)) {
		return FALSE;
	}

	position = manager->conversations->len;
	g_ptr_array_add(manager->conversations, g_object_ref(conversation));

	/* Register our signals that need to be propagated. */
	g_signal_connect_object(conversation, "notify",
	                        G_CALLBACK(purple_conversation_manager_conversation_changed_cb),
	                        manager, 0);
	g_signal_connect_object(conversation, "present",
	                        G_CALLBACK(purple_conversation_manager_present_conversation_cb),
	                        manager, 0);

	/* Tell everyone about the new conversation. */
	g_signal_emit(manager, signals[SIG_ADDED], 0, conversation);
	g_list_model_items_changed(G_LIST_MODEL(manager), position, 0, 1);
	g_object_notify_by_pspec(G_OBJECT(manager), properties[PROP_N_ITEMS]);

	return TRUE;
}

PurpleConversationManager *
purple_conversation_manager_new(const char *filename) {
	return g_object_new(
		PURPLE_TYPE_CONVERSATION_MANAGER,
		"filename", filename,
		NULL);
}

PurpleConversationManager *
purple_conversation_manager_get_default(void) {
	return default_manager;
}

GListModel *
purple_conversation_manager_get_default_as_model(void) {
	if(PURPLE_IS_CONVERSATION_MANAGER(default_manager)) {
		return G_LIST_MODEL(default_manager);
	}

	return NULL;
}

const char *
purple_conversation_manager_get_filename(PurpleConversationManager *manager) {
	g_return_val_if_fail(PURPLE_IS_CONVERSATION_MANAGER(manager), NULL);

	return manager->filename;
}

GList *
purple_conversation_manager_get_all(PurpleConversationManager *manager) {
	GList *result = NULL;
	g_return_val_if_fail(PURPLE_IS_CONVERSATION_MANAGER(manager), NULL);

	for(guint i = 0; i < manager->conversations->len; i++) {
		PurpleConversation *conversation = NULL;

		conversation = g_ptr_array_index(manager->conversations, i);
		result = g_list_append(result, conversation);
	}

	return result;
}

PurpleConversation *
purple_conversation_manager_find_dm(PurpleConversationManager *manager,
                                    PurpleContact *contact)
{
	PurpleAccount *contact_account = NULL;
	PurpleContactInfo *info = NULL;

	g_return_val_if_fail(PURPLE_IS_CONVERSATION_MANAGER(manager), NULL);
	g_return_val_if_fail(PURPLE_IS_CONTACT(contact), NULL);

	info = PURPLE_CONTACT_INFO(contact);
	contact_account = purple_contact_get_account(contact);

	for(guint i = 0; i < manager->conversations->len; i++) {
		PurpleAccount *conversation_account = NULL;
		PurpleConversation *conversation = NULL;
		PurpleConversationMembers *members = NULL;

		conversation = g_ptr_array_index(manager->conversations, i);
		conversation_account = purple_conversation_get_account(conversation);
		if(conversation_account != contact_account) {
			continue;
		}

		if(!purple_conversation_is_dm(conversation)) {
			continue;
		}

		members = purple_conversation_get_members(conversation);
		if(purple_conversation_members_has_member(members, info, NULL)) {
			return conversation;
		}
	}

	return NULL;
}

PurpleConversation *
purple_conversation_manager_find_with_id(PurpleConversationManager *manager,
                                         PurpleAccount *account,
                                         const char *id)
{
	g_return_val_if_fail(PURPLE_IS_CONVERSATION_MANAGER(manager), NULL);
	g_return_val_if_fail(PURPLE_IS_ACCOUNT(account), NULL);

	for(guint i = 0; i < manager->conversations->len; i++) {
		PurpleConversation *conversation = NULL;

		conversation = g_ptr_array_index(manager->conversations, i);
		if(purple_conversation_get_account(conversation) != account) {
			continue;
		}

		if(purple_strequal(purple_conversation_get_id(conversation), id)) {
			return conversation;
		}
	}

	return NULL;
}

gboolean
purple_conversation_manager_remove(PurpleConversationManager *manager,
                                   PurpleConversation *conversation)
{
	guint position = 0;

	g_return_val_if_fail(PURPLE_IS_CONVERSATION_MANAGER(manager), FALSE);
	g_return_val_if_fail(PURPLE_IS_CONVERSATION(conversation), FALSE);

	if(!g_ptr_array_find(manager->conversations, conversation, &position)) {
		return FALSE;
	}

	/* Make sure we have a reference in case we need to emit signals. */
	g_object_ref(conversation);

	g_ptr_array_remove_index(manager->conversations, position);

	/* Disconnect all the signals we added for propagation. */
	g_signal_handlers_disconnect_by_func(conversation,
	                                     purple_conversation_manager_conversation_changed_cb,
	                                     manager);
	g_signal_handlers_disconnect_by_func(conversation,
	                                     purple_conversation_manager_present_conversation_cb,
	                                     manager);

	/* Tell everyone about the removed conversation. */
	g_signal_emit(manager, signals[SIG_REMOVED], 0, conversation);
	g_list_model_items_changed(G_LIST_MODEL(manager), position, 1, 0);
	g_object_notify_by_pspec(G_OBJECT(manager), properties[PROP_N_ITEMS]);

	g_object_unref(conversation);

	return TRUE;
}
