/*
 * 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 "purplecommandmanager.h"
#include "purplecommandmanagerprivate.h"

#include "purplecommands.h"
#include "util.h"

struct _PurpleCommandManager {
	GObject parent;

	GPtrArray *commands;
};

static PurpleCommandManager *default_manager = NULL;

/******************************************************************************
 * GListModel Implementation
 *****************************************************************************/
static GType
purple_command_manager_get_item_type(G_GNUC_UNUSED GListModel *list) {
	return PURPLE_TYPE_COMMAND;
}

static guint
purple_command_manager_get_n_items(GListModel *list) {
	PurpleCommandManager *manager = PURPLE_COMMAND_MANAGER(list);

	return manager->commands->len;
}

static gpointer
purple_command_manager_get_item(GListModel *list, guint position) {
	PurpleCommandManager *manager = PURPLE_COMMAND_MANAGER(list);
	PurpleCommand *command = NULL;

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

	return command;
}

static void
purple_command_manager_list_model_init(GListModelInterface *iface) {
	iface->get_item_type = purple_command_manager_get_item_type;
	iface->get_n_items = purple_command_manager_get_n_items;
	iface->get_item = purple_command_manager_get_item;
}

/******************************************************************************
 * GObject Implementation
 *****************************************************************************/
G_DEFINE_FINAL_TYPE_WITH_CODE(PurpleCommandManager, purple_command_manager,
                              G_TYPE_OBJECT,
                              G_IMPLEMENT_INTERFACE(G_TYPE_LIST_MODEL,
                                                    purple_command_manager_list_model_init))

static void
purple_command_manager_finalize(GObject *obj) {
	PurpleCommandManager *manager = PURPLE_COMMAND_MANAGER(obj);

	g_clear_pointer(&manager->commands, g_ptr_array_unref);

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

static void
purple_command_manager_init(PurpleCommandManager *manager) {
	manager->commands = g_ptr_array_new_full(10, g_object_unref);
}

static void
purple_command_manager_class_init(PurpleCommandManagerClass *klass) {
	GObjectClass *obj_class = G_OBJECT_CLASS(klass);

	obj_class->finalize = purple_command_manager_finalize;
}

static gboolean
purple_command_manager_commands_equal(gconstpointer a, gconstpointer b) {
	PurpleCommand *command1 = (gpointer)a;
	PurpleCommand *command2 = (gpointer)b;
	const char *name1 = NULL;
	const char *name2 = NULL;

	name1 = purple_command_get_name(command1);
	name2 = purple_command_get_name(command2);

	if(purple_strequal(name1, name2)) {
		const char *source1 = NULL;
		const char *source2 = NULL;

		source1 = purple_command_get_source(command1);
		source2 = purple_command_get_source(command2);

		if(purple_strequal(source1, source2)) {
			return TRUE;
		}
	}

	return FALSE;
}

/******************************************************************************
 * Private API
 *****************************************************************************/
void
purple_command_manager_startup(void) {
	if(default_manager == NULL) {
		default_manager = purple_command_manager_new();
		if(PURPLE_IS_COMMAND_MANAGER(default_manager)) {
			PurpleCommand *command = NULL;

			command = purple_say_command_new();
			purple_command_manager_add(default_manager, command);

			command = purple_action_command_new();
			purple_command_manager_add(default_manager, command);

			g_object_add_weak_pointer(G_OBJECT(default_manager),
			                          (gpointer *)&default_manager);
		}
	}
}

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

/******************************************************************************
 * Public API
 *****************************************************************************/
void
purple_command_manager_add(PurpleCommandManager *manager,
                           PurpleCommand *command)
{
	gboolean found = FALSE;

	g_return_if_fail(PURPLE_IS_COMMAND_MANAGER(manager));
	g_return_if_fail(PURPLE_IS_COMMAND(command));

	/* If the manager already knows about the command, we do nothing. */
	found = g_ptr_array_find_with_equal_func(manager->commands, command,
	                                         purple_command_manager_commands_equal,
	                                         NULL);
	if(!found) {
		g_ptr_array_add(manager->commands, command);

		g_list_model_items_changed(G_LIST_MODEL(manager),
		                           manager->commands->len - 1, 0, 1);
	} else {
		g_object_unref(command);
	}
}

PurpleCommand *
purple_command_manager_find(PurpleCommandManager *manager,
                            PurpleConversation *conversation,
                            const char *name)
{
	PurpleCommand *command = NULL;
	PurpleTags *conversation_tags = NULL;
	int current_priority = 0;

	g_return_val_if_fail(PURPLE_IS_COMMAND_MANAGER(manager), NULL);
	g_return_val_if_fail(!purple_strempty(name), NULL);

	if(PURPLE_IS_CONVERSATION(conversation)) {
		conversation_tags = purple_conversation_get_tags(conversation);
	}

	for(guint i = 0; i < manager->commands->len; i++) {
		PurpleCommand *candidate = NULL;
		const char *candidate_name = NULL;
		int candidate_priority = 0;

		candidate = g_ptr_array_index(manager->commands, i);
		if(!PURPLE_IS_COMMAND(candidate)) {
			continue;
		}

		candidate_name = purple_command_get_name(candidate);
		if(!purple_strequal(candidate_name, name)) {
			continue;
		}

		if(conversation_tags != NULL) {
			PurpleTags *command_tags = purple_command_get_tags(candidate);

			if(!purple_tags_contains(conversation_tags, command_tags)) {
				continue;
			}
		}

		candidate_priority = purple_command_get_priority(candidate);

		if(command == NULL || candidate_priority > current_priority) {
			command = candidate;
			current_priority = candidate_priority;
		}
	}

	return command;
}

GListModel *
purple_command_manager_find_all(PurpleCommandManager *manager,
                                PurpleConversation *conversation,
                                const char *name)
{
	PurpleTags *conversation_tags = NULL;
	GListStore *commands = NULL;

	g_return_val_if_fail(PURPLE_IS_COMMAND_MANAGER(manager), NULL);
	g_return_val_if_fail(!purple_strempty(name), NULL);

	if(PURPLE_IS_CONVERSATION(conversation)) {
		conversation_tags = purple_conversation_get_tags(conversation);
	}

	commands = g_list_store_new(PURPLE_TYPE_COMMAND);

	for(guint i = 0; i < manager->commands->len; i++) {
		PurpleCommand *command = NULL;
		const char *command_name = NULL;

		command = g_ptr_array_index(manager->commands, i);
		if(!PURPLE_IS_COMMAND(command)) {
			continue;
		}

		command_name = purple_command_get_name(command);
		if(!purple_strequal(command_name, name)) {
			continue;
		}

		if(conversation_tags != NULL) {
			PurpleTags *command_tags = purple_command_get_tags(command);

			if(!purple_tags_contains(conversation_tags, command_tags)) {
				continue;
			}
		}

		g_list_store_append(commands, command);
	}

	return G_LIST_MODEL(commands);
}

gboolean
purple_command_manager_find_and_execute(PurpleCommandManager *manager,
                                        PurpleConversation *conversation,
                                        const char *command_line)
{
	PurpleCommand *command = NULL;
	GStrv params = NULL;
	char *command_name = NULL;
	gboolean ret = FALSE;

	g_return_val_if_fail(PURPLE_IS_COMMAND_MANAGER(manager), FALSE);
	g_return_val_if_fail(PURPLE_IS_CONVERSATION(conversation), FALSE);
	g_return_val_if_fail(!purple_strempty(command_line), FALSE);

	params = g_strsplit(command_line, " ", -1);
	command_name = params[0];

	command = purple_command_manager_find(manager, conversation, command_name);
	if(PURPLE_IS_COMMAND(command)) {
		purple_command_executev(command, conversation, params + 1);

		ret = TRUE;
	}

	g_strfreev(params);

	return ret;
}

PurpleCommandManager *
purple_command_manager_get_default(void) {
	return default_manager;
}

GListModel *
purple_command_manager_get_default_as_model(void) {
	return G_LIST_MODEL(default_manager);
}

GListModel *
purple_command_manager_get_commands_for_conversation(PurpleCommandManager *manager,
                                                     PurpleConversation *conversation)
{
	PurpleTags *conversation_tags = NULL;
	GListStore *commands = NULL;

	g_return_val_if_fail(PURPLE_IS_COMMAND_MANAGER(manager), NULL);
	g_return_val_if_fail(PURPLE_IS_CONVERSATION(conversation), NULL);

	commands = g_list_store_new(PURPLE_TYPE_COMMAND);
	conversation_tags = purple_conversation_get_tags(conversation);

	for(guint i = 0; i < manager->commands->len; i++) {
		PurpleCommand *command = NULL;
		PurpleTags *command_tags = NULL;

		command = g_ptr_array_index(manager->commands, i);
		command_tags = purple_command_get_tags(command);

		if(purple_tags_contains(conversation_tags, command_tags)) {
			g_list_store_append(commands, command);
		}
	}

	return G_LIST_MODEL(commands);
}

PurpleCommandManager *
purple_command_manager_new(void) {
	return g_object_new(PURPLE_TYPE_COMMAND_MANAGER, NULL);
}

gboolean
purple_command_manager_remove(PurpleCommandManager *manager, const char *name,
                              const char *source)
{
	g_return_val_if_fail(PURPLE_IS_COMMAND_MANAGER(manager), FALSE);

	for(guint i = 0; i < manager->commands->len; i++) {
		PurpleCommand *command = NULL;
		const char *command_name = NULL;
		const char *command_source = NULL;

		command = g_ptr_array_index(manager->commands, i);
		if(!PURPLE_IS_COMMAND(command)) {
			continue;
		}

		command_name = purple_command_get_name(command);
		command_source = purple_command_get_source(command);
		if(purple_strequal(command_name, name) &&
		   purple_strequal(command_source, source))
		{
			g_ptr_array_remove_index(manager->commands, i);

			g_list_model_items_changed(G_LIST_MODEL(manager), i, 1, 0);

			return TRUE;
		}
	}

	return FALSE;
}

void
purple_command_manager_remove_all_with_source(PurpleCommandManager *manager,
                                              const char *source)
{
	g_return_if_fail(PURPLE_IS_COMMAND_MANAGER(manager));
	g_return_if_fail(!purple_strempty(source));

	/* Since GPtrArray shifts everything down on a remove, we only increment
	 * when we haven't removed a command.
	 */
	for(guint i = 0; i < manager->commands->len;) {
		PurpleCommand *command = NULL;
		const char *command_source = NULL;

		command = g_ptr_array_index(manager->commands, i);
		if(!PURPLE_IS_COMMAND(command)) {
			continue;
		}

		command_source = purple_command_get_source(command);
		if(purple_strequal(command_source, source)) {
			g_ptr_array_remove_index(manager->commands, i);

			/* TODO: optimize this so we notify when a group of items is
			 * removed instead of notifying for every remove.
			 */
			g_list_model_items_changed(G_LIST_MODEL(manager), i, 1, 0);
		} else {
			i++;
		}
	}
}
