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

#include <seagull.h>

#include "purpleconversationmanagerseagullbackend.h"

#include "purpleaccountmanager.h"

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

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

struct _PurpleConversationManagerSeagullBackend {
	PurpleConversationManagerBackend parent;

	char *filename;
	SeagullSqlite3 *db;

	SeagullStatement *delete_properties;
	SeagullStatement *delete_tags;
	SeagullStatement *insert_properties;
	SeagullStatement *insert_tags;
	SeagullStatement *query_properties;
	SeagullStatement *query_tags;
};

#define RESOURCE_PATH "/im/pidgin/libpurple/conversationmanager"

/******************************************************************************
 * Helpers
 *****************************************************************************/

static void
purple_conversation_manager_seagull_backend_set_filename(PurpleConversationManagerSeagullBackend *backend,
                                                         const char *filename)
{
	g_return_if_fail(PURPLE_IS_CONVERSATION_MANAGER_SEAGULL_BACKEND(backend));

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

/******************************************************************************
 * Delete Implementation
 *****************************************************************************/
static gboolean
purple_conversation_manager_seagull_backend_delete_conversation_tags(PurpleConversationManagerSeagullBackend *backend,
                                                                     const char *conversation_id,
                                                                     const char *account_id,
                                                                     GError **error)
{
	GError *local_error = NULL;
	gboolean success = FALSE;

	g_return_val_if_fail(PURPLE_IS_CONVERSATION_MANAGER_SEAGULL_BACKEND(backend),
	                     FALSE);
	g_return_val_if_fail(!birb_str_is_empty(conversation_id), FALSE);
	g_return_val_if_fail(!birb_str_is_empty(account_id), FALSE);

	/* Clear any existing usage. */
	if(!seagull_statement_clear_bindings(backend->delete_tags, error)) {
		return FALSE;
	}

	if(!seagull_statement_reset(backend->delete_tags, error)) {
		return FALSE;
	}

	/* Bind the conversation id to the delete statement. */
	success = seagull_statement_bind_text(backend->delete_tags,
	                                      ":conversation_id",
	                                      conversation_id,
	                                      -1,
	                                      NULL,
	                                      error);
	if(!success) {
		return FALSE;
	}

	/* Bind the account id to the delete statement. */
	success = seagull_statement_bind_text(backend->delete_tags,
	                                      ":account_id",
	                                      account_id,
	                                      -1,
	                                      NULL,
	                                      error);
	if(!success) {
		return FALSE;
	}

	seagull_statement_step(backend->delete_tags, &local_error);
	if(local_error != NULL) {
		g_propagate_error(error, local_error);

		return FALSE;
	}

	return TRUE;
}

static gboolean
purple_conversation_manager_seagull_backend_delete_conversation_properties(PurpleConversationManagerSeagullBackend *backend,
                                                                           const char *conversation_id,
                                                                           const char *account_id,
                                                                           GError **error)
{
	GError *local_error = NULL;
	gboolean success = FALSE;

	g_return_val_if_fail(PURPLE_IS_CONVERSATION_MANAGER_SEAGULL_BACKEND(backend),
	                     FALSE);
	g_return_val_if_fail(!birb_str_is_empty(conversation_id), FALSE);
	g_return_val_if_fail(!birb_str_is_empty(account_id), FALSE);

	/* Clear any existing usage. */
	if(!seagull_statement_clear_bindings(backend->delete_properties, error)) {
		return FALSE;
	}

	if(!seagull_statement_reset(backend->delete_properties, error)) {
		return FALSE;
	}

	/* Bind the conversation id to the delete statement. */
	success = seagull_statement_bind_text(backend->delete_properties,
	                                      ":conversation_id",
	                                      conversation_id,
	                                      -1,
	                                      NULL,
	                                      error);
	if(!success) {
		return FALSE;
	}

	/* Bind the account id to the delete statement. */
	success = seagull_statement_bind_text(backend->delete_properties,
	                                      ":account_id",
	                                      account_id,
	                                      -1,
	                                      NULL,
	                                      error);
	if(!success) {
		return FALSE;
	}

	seagull_statement_step(backend->delete_properties, &local_error);
	if(local_error != NULL) {
		g_propagate_error(error, local_error);

		return FALSE;
	}

	return TRUE;
}

static void
purple_conversation_manager_seagull_backend_delete_conversation_async(PurpleConversationManagerBackend *purple_backend,
                                                                      PurpleConversation *conversation,
                                                                      GCancellable *cancellable,
                                                                      GAsyncReadyCallback callback,
                                                                      gpointer data)
{
	PurpleConversationManagerSeagullBackend *backend = NULL;
	PurpleAccount *account = NULL;
	GError *error = NULL;
	GTask *task = NULL;
	const char *conversation_id = NULL;
	const char *account_id = NULL;
	gboolean success = FALSE;

	backend = PURPLE_CONVERSATION_MANAGER_SEAGULL_BACKEND(purple_backend);

	task = g_task_new(G_OBJECT(backend), cancellable, callback, data);

	/* Start a transaction so that everything is atomic. */
	if(!seagull_transaction_begin(backend->db, &error)) {
		g_task_return_error(task, error);

		g_clear_object(&task);

		return;
	}

	/* Grab the conversation and account ids as we need them for everything. */
	conversation_id = purple_conversation_get_id(conversation);
	account = purple_conversation_get_account(conversation);
	account_id = purple_account_get_id(account);

	/* Delete the properties. We do this first, because it is used to restore
	 * conversations. So if it fails to delete, we might be able to salvage a
	 * rejoin as the other data still exists. This would then allow the user
	 * to attempt to leave again, and hopefully it'll work that time.
	 */
	success = purple_conversation_manager_seagull_backend_delete_conversation_properties(backend,
	                                                                                     conversation_id,
	                                                                                     account_id,
	                                                                                     &error);
	if(error != NULL || !success) {
		g_task_return_error(task, error);

		g_clear_error(&error);
		if(!seagull_transaction_rollback(backend->db, &error)) {
			g_warning("failed to rollback transaction: %s", error->message);
			g_clear_error(&error);
		}

		g_clear_object(&task);

		return;
	}

	/* Delete the tags. */
	success = purple_conversation_manager_seagull_backend_delete_conversation_tags(backend,
	                                                                               conversation_id,
	                                                                               account_id,
	                                                                               &error);
	if(error != NULL || !success) {
		g_task_return_error(task, error);

		g_clear_error(&error);
		if(!seagull_transaction_rollback(backend->db, &error)) {
			g_warning("failed to rollback transaction: %s", error->message);
			g_clear_error(&error);
		}

		g_clear_object(&task);

		return;
	}

	/* Commit the transaction. */
	if(!seagull_transaction_commit(backend->db, &error)) {
		g_task_return_error(task, error);
	} else {
		g_task_return_boolean(task, TRUE);
	}

	g_clear_object(&task);
}

static gboolean
purple_conversation_manager_seagull_backend_delete_conversation_finish(PurpleConversationManagerBackend *backend,
                                                                       GAsyncResult *result,
                                                                       GError **error)
{
	g_return_val_if_fail(PURPLE_IS_CONVERSATION_MANAGER_SEAGULL_BACKEND(backend),
	                     FALSE);
	g_return_val_if_fail(g_task_is_valid(result, backend), FALSE);

	return g_task_propagate_boolean(G_TASK(result), error);
}

/******************************************************************************
 * Load Implementation
 *****************************************************************************/
static void
purple_conversation_manager_seagull_backend_load_conversation_tags(PurpleConversationManagerSeagullBackend *backend,
                                                                   PurpleConversation *conversation,
                                                                   const char *account_id,
                                                                   const char *conversation_id,
                                                                   GError **error)
{
	PurpleTags *tags = NULL;
	GError *local_error = NULL;

	tags = purple_conversation_get_tags(conversation);

	/* Conversations have some default tags when created, but we need to
	 * replace everything so we clear those.
	 */
	purple_tags_remove_all(tags);

	/* Reset the statement. */
	seagull_statement_reset(backend->query_tags, &local_error);
	if(local_error != NULL) {
		g_propagate_error(error, local_error);

		return;
	}

	/* Bind the account id. */
	seagull_statement_bind_text(backend->query_tags, ":account_id", account_id,
	                            -1, NULL, &local_error);
	if(local_error != NULL) {
		g_propagate_error(error, local_error);

		return;
	}

	/* Bind the conversation id. */
	seagull_statement_bind_text(backend->query_tags, ":conversation_id",
	                            conversation_id, -1, NULL, &local_error);
	if(local_error != NULL) {
		g_propagate_error(error, local_error);

		return;
	}

	while(seagull_statement_step(backend->query_tags, &local_error)) {
		const char *tag = NULL;

		tag = seagull_statement_column_text(backend->query_tags, "tag",
		                                    &local_error);

		if(local_error != NULL) {
			g_propagate_error(error, local_error);

			return;
		}

		purple_tags_add(tags, tag);
	}

	if(local_error != NULL) {
		g_propagate_error(error, local_error);
	}
}

static void
purple_conversation_manager_seagull_backend_load_conversations_async(PurpleConversationManagerBackend *purple_backend,
                                                                     GCancellable *cancellable,
                                                                     GAsyncReadyCallback callback,
                                                                     gpointer data)
{
	PurpleAccountManager *account_manager = NULL;
	PurpleConversationManagerSeagullBackend *backend = NULL;
	GError *error = NULL;
	GListStore *conversations = NULL;
	GTask *task = NULL;

	backend = PURPLE_CONVERSATION_MANAGER_SEAGULL_BACKEND(purple_backend);

	task = g_task_new(G_OBJECT(backend), cancellable, callback, data);

	seagull_statement_reset(backend->query_properties, &error);
	if(error != NULL) {
		g_task_return_error(task, error);

		g_clear_object(&task);

		return;
	}

	account_manager = purple_account_manager_get_default();
	conversations = g_list_store_new(PURPLE_TYPE_CONVERSATION);

	while(seagull_statement_step(backend->query_properties, &error)) {
		PurpleAccount *account = NULL;
		PurpleConversation *conversation = NULL;
		const char *account_id = NULL;
		const char *conversation_id = NULL;
		gint type = PURPLE_CONVERSATION_TYPE_UNSET;
		gboolean federated = FALSE;

		/* Grab the account id and attempt to find the account. */
		account_id = seagull_statement_column_text(backend->query_properties,
		                                           "account_id", &error);
		if(error != NULL) {
			g_warning("failed to read account id: %s", error->message);
			g_clear_error(&error);

			continue;
		}

		account = purple_account_manager_find_by_id(account_manager,
		                                            account_id);
		if(!PURPLE_IS_ACCOUNT(account)) {
			g_warning("failed to find account for id %s", account_id);

			continue;
		}

		conversation_id = seagull_statement_column_text(backend->query_properties,
		                                                "conversation_id",
		                                                &error);
		if(error != NULL) {
			g_warning("failed to read conversation id: %s", error->message);
			g_clear_error(&error);

			continue;
		}

		type = seagull_statement_column_enum(backend->query_properties, "type",
		                                     &error);
		if(error != NULL) {
			g_warning("failed to read type: %s", error->message);
			g_clear_error(&error);

			continue;
		}

		federated = seagull_statement_column_int(backend->query_properties,
		                                         "federated", &error);
		if(error != NULL) {
			g_warning("failed to read federated: %s", error->message);
			g_clear_error(&error);

			continue;
		}

		/* We have all the construct only properties, so let's create the
		 * instance.
		 */
		conversation = g_object_new(
			PURPLE_TYPE_CONVERSATION,
			"account", account,
			"federated", federated,
			"id", conversation_id,
			"type", type,
			NULL);

		/* Now set the rest of the properties. */
		seagull_statement_column_object(backend->query_properties, "conv_",
		                                G_OBJECT(conversation), &error);

		if(error != NULL) {
			g_warning("failed to read object properties: %s", error->message);
			g_clear_error(&error);

			g_clear_object(&conversation);

			continue;
		}

		purple_conversation_manager_seagull_backend_load_conversation_tags(backend,
		                                                                   conversation,
		                                                                   account_id,
		                                                                   conversation_id,
		                                                                   &error);
		if(error != NULL) {
			g_warning("failed to load tags for conversation %s: %s",
			          conversation_id, error->message);

			g_clear_error(&error);
			g_clear_object(&conversation);

			continue;
		}

		g_list_store_append(conversations, conversation);

		g_clear_object(&conversation);
	}

	if(error != NULL) {
		g_task_return_error(task, error);
	} else {
		g_task_return_pointer(task, conversations, g_object_unref);
	}

	g_clear_object(&task);
}

static GListModel *
purple_conversation_manager_seagull_backend_load_conversations_finish(PurpleConversationManagerBackend *backend,
                                                                      GAsyncResult *result,
                                                                      GError **error)
{
	g_return_val_if_fail(PURPLE_IS_CONVERSATION_MANAGER_SEAGULL_BACKEND(backend),
	                     FALSE);
	g_return_val_if_fail(g_task_is_valid(result, backend), FALSE);

	return g_task_propagate_pointer(G_TASK(result), error);
}

/******************************************************************************
 * Save Implementation
 *****************************************************************************/
static gboolean
purple_conversation_manager_seagull_backend_save_conversation_properties(PurpleConversationManagerSeagullBackend *backend,
                                                                         PurpleConversation *conversation,
                                                                         GError **error)
{
	PurpleAccount *account = NULL;
	PurpleContactInfo *contact = NULL;
	gboolean success = FALSE;

	/* Clear any existing usage. */
	if(!seagull_statement_clear_bindings(backend->insert_properties, error)) {
		return FALSE;
	}

	if(!seagull_statement_reset(backend->insert_properties, error)) {
		return FALSE;
	}

	/* Bind the properties for the conversation. */
	success = seagull_statement_bind_object(backend->insert_properties,
	                                        "conv_", G_OBJECT(conversation),
	                                        error);
	if(!success) {
		return FALSE;
	}

	/* Bind the account */
	account = purple_conversation_get_account(conversation);
	success = seagull_statement_bind_text(backend->insert_properties,
	                                      ":account_id",
	                                      purple_account_get_id(account),
	                                      -1,
	                                      NULL,
	                                      error);
	if(!success) {
		return FALSE;
	}

	/* If we have a creator, bind it. */
	contact = purple_conversation_get_creator(conversation);
	if(PURPLE_IS_CONTACT_INFO(contact)) {
		success = seagull_statement_bind_text(backend->insert_properties,
		                                      ":creator_id",
		                                      purple_contact_info_get_id(contact),
		                                      -1,
		                                      NULL,
		                                      error);
	} else {
		success = seagull_statement_bind_null(backend->insert_properties,
		                                      ":creator_id",
		                                      error);
	}

	if(!success) {
		return FALSE;
	}

	/* If we have a topic author, bind it. */
	contact = purple_conversation_get_topic_author(conversation);
	if(PURPLE_IS_CONTACT_INFO(contact)) {
		success = seagull_statement_bind_text(backend->insert_properties,
		                                      ":topic_author_id",
		                                      purple_contact_info_get_id(contact),
		                                      -1,
		                                      NULL,
		                                      error);
	} else {
		success = seagull_statement_bind_null(backend->insert_properties,
		                                      ":topic_author_id",
		                                      error);
	}

	if(!success) {
		return FALSE;
	}

	/* The return value of step is whether or not there is data to read. Since
	 * this is an insert statement, we can ignore it.
	 */
	seagull_statement_step(backend->insert_properties, error);
	if(error != NULL && *error != NULL) {
		return FALSE;
	}

	return TRUE;
}

static gboolean
purple_conversation_manager_seagull_backend_save_conversation_tags(PurpleConversationManagerSeagullBackend *backend,
                                                                   PurpleConversation *conversation,
                                                                   GError **error)
{
	PurpleAccount *account = NULL;
	PurpleTags *tags = NULL;
	GListModel *model = NULL;
	const char *conversation_id = NULL;
	const char *account_id = NULL;
	gboolean success = FALSE;
	guint n_items = 0;

	/* Grab the conversation and account ids as we need them for everything. */
	conversation_id = purple_conversation_get_id(conversation);
	account = purple_conversation_get_account(conversation);
	account_id = purple_account_get_id(account);

	/* Delete the existing tags. */
	success = purple_conversation_manager_seagull_backend_delete_conversation_tags(backend,
	                                                                               conversation_id,
	                                                                               account_id,
	                                                                               error);
	if(!success) {
		return FALSE;
	}

	/* Bind the conversation id to the insert statement. */
	success = seagull_statement_bind_text(backend->insert_tags,
	                                      ":conversation_id",
	                                      conversation_id,
	                                      -1,
	                                      NULL,
	                                      error);
	if(!success) {
		return FALSE;
	}

	/* Bind the account id to the insert statement. */
	success = seagull_statement_bind_text(backend->insert_tags,
	                                      ":account_id",
	                                      account_id,
	                                      -1,
	                                      NULL,
	                                      error);
	if(!success) {
		return FALSE;
	}

	/* Now run through tags and insert them. */
	tags = purple_conversation_get_tags(conversation);
	model = G_LIST_MODEL(tags);
	n_items = g_list_model_get_n_items(model);
	for(guint i = 0; i < n_items; i++) {
		BirbStringObject *obj = NULL;
		const char *tag = NULL;

		obj = g_list_model_get_item(model, i);
		tag = birb_string_object_get_string(obj);

		success = seagull_statement_bind_text(backend->insert_tags,
		                                      ":tag",
		                                      g_strdup(tag),
		                                      -1,
		                                      g_free,
		                                      error);
		g_clear_object(&obj);

		if(!success) {
			return FALSE;
		}

		/* Step the statement. */
		seagull_statement_step(backend->insert_tags, error);
		if(error != NULL && *error != NULL) {
			char *expanded = NULL;

			expanded = seagull_statement_get_expanded_sql(backend->insert_tags);
			g_warning("sql: %s", expanded);
			seagull_free(expanded);

			return FALSE;
		}

		if(!seagull_statement_reset(backend->insert_tags, error)) {
			return FALSE;
		}
	}

	return TRUE;
}

static void
purple_conversation_manager_seagull_backend_save_conversation_async(PurpleConversationManagerBackend *purple_backend,
                                                                    PurpleConversation *conversation,
                                                                    GCancellable *cancellable,
                                                                    GAsyncReadyCallback callback,
                                                                    gpointer data)
{
	PurpleConversationManagerSeagullBackend *backend = NULL;
	GError *error = NULL;
	GTask *task = NULL;
	gboolean success = FALSE;

	backend = PURPLE_CONVERSATION_MANAGER_SEAGULL_BACKEND(purple_backend);

	task = g_task_new(G_OBJECT(backend), cancellable, callback, data);

	/* Start a transaction so that everything is atomic. */
	if(!seagull_transaction_begin(backend->db, &error)) {
		g_task_return_error(task, error);

		g_clear_object(&task);

		return;
	}

	/* Save the conversation properties. */
	success = purple_conversation_manager_seagull_backend_save_conversation_properties(backend,
	                                                                                   conversation,
	                                                                                   &error);
	if(!success) {
		g_task_return_error(task, error);

		g_clear_error(&error);
		if(!seagull_transaction_rollback(backend->db, &error)) {
			g_warning("failed to rollback transaction: %s", error->message);
			g_clear_error(&error);
		}

		g_clear_object(&task);

		return;
	}

	/* Save the conversation tags. */
	success = purple_conversation_manager_seagull_backend_save_conversation_tags(backend,
	                                                                             conversation,
	                                                                             &error);
	if(!success) {
		g_task_return_error(task, error);

		g_clear_error(&error);
		if(!seagull_transaction_rollback(backend->db, &error)) {
			g_warning("failed to rollback transaction: %s", error->message);
			g_clear_error(&error);
		}

		g_clear_object(&task);

		return;
	}

	/* Commit the transaction. */
	if(!seagull_transaction_commit(backend->db, &error)) {
		g_task_return_error(task, error);
	} else {
		g_task_return_boolean(task, TRUE);
	}

	g_clear_object(&task);
}

static gboolean
purple_conversation_manager_seagull_backend_save_conversation_finish(PurpleConversationManagerBackend *backend,
                                                                     GAsyncResult *result,
                                                                     GError **error)
{
	g_return_val_if_fail(PURPLE_IS_CONVERSATION_MANAGER_SEAGULL_BACKEND(backend),
	                     FALSE);
	g_return_val_if_fail(g_task_is_valid(result, backend), FALSE);

	return g_task_propagate_boolean(G_TASK(result), error);
}

/******************************************************************************
 * GInitable Implementation
 *****************************************************************************/
static gboolean
purple_conversation_manager_seagull_backend_initable_init(GInitable *initable,
                                                          G_GNUC_UNUSED GCancellable *cancellable,
                                                          GError **error)
{
	PurpleConversationManagerSeagullBackend *backend = NULL;
	SeagullStatement *stmt = NULL;
	GError *local_error = NULL;
	gboolean result = FALSE;
	const char *migrations[] = {
		"01-initial.sql",
		NULL
	};

	backend = PURPLE_CONVERSATION_MANAGER_SEAGULL_BACKEND(initable);

	if(!birb_str_is_empty(backend->filename)) {
		backend->db = seagull_db_new_from_file(backend->filename,
		                                       &local_error);
	} else {
		backend->db = seagull_db_new_in_memory(&local_error);
	}

	if(local_error != NULL) {
		g_propagate_error(error, local_error);

		return FALSE;
	}

	/* Run the migrations. */
	result = seagull_migrations_run_from_resources(backend->db,
	                                               RESOURCE_PATH "/migrations",
	                                               migrations,
	                                               &local_error);

	if(!result) {
		g_propagate_error(error, local_error);

		return FALSE;
	}

	stmt = seagull_statement_new_from_resource(backend->db,
	                                           RESOURCE_PATH "/statements/delete-properties.sql",
	                                           &local_error);
	if(local_error != NULL) {
		g_propagate_error(error, local_error);

		return FALSE;
	}
	backend->delete_properties = stmt;

	stmt = seagull_statement_new_from_resource(backend->db,
	                                           RESOURCE_PATH "/statements/delete-tags.sql",
	                                           &local_error);
	if(local_error != NULL) {
		g_propagate_error(error, local_error);

		return FALSE;
	}
	backend->delete_tags = stmt;

	stmt = seagull_statement_new_from_resource(backend->db,
	                                           RESOURCE_PATH "/statements/insert-properties.sql",
	                                           &local_error);
	if(local_error != NULL) {
		g_propagate_error(error, local_error);

		return FALSE;
	}
	backend->insert_properties = stmt;

	stmt = seagull_statement_new_from_resource(backend->db,
	                                           RESOURCE_PATH "/statements/insert-tags.sql",
	                                           &local_error);
	if(local_error != NULL) {
		g_propagate_error(error, local_error);

		return FALSE;
	}
	backend->insert_tags = stmt;

	stmt = seagull_statement_new_from_resource(backend->db,
	                                           RESOURCE_PATH "/statements/query-properties.sql",
	                                           &local_error);
	if(local_error != NULL) {
		g_propagate_error(error, local_error);

		return FALSE;
	}
	backend->query_properties = stmt;

	stmt = seagull_statement_new_from_resource(backend->db,
	                                           RESOURCE_PATH "/statements/query-tags.sql",
	                                           &local_error);
	if(local_error != NULL) {
		g_propagate_error(error, local_error);

		return FALSE;
	}
	backend->query_tags = stmt;

	return TRUE;
}

static void
purple_conversation_manager_seagull_backend_initable_iface_init(GInitableIface *iface)
{
	iface->init = purple_conversation_manager_seagull_backend_initable_init;
}

/******************************************************************************
 * GObject Implementation
 *****************************************************************************/
G_DEFINE_FINAL_TYPE_WITH_CODE(PurpleConversationManagerSeagullBackend,
                              purple_conversation_manager_seagull_backend,
                              PURPLE_TYPE_CONVERSATION_MANAGER_BACKEND,
                              G_IMPLEMENT_INTERFACE(G_TYPE_INITABLE,
                                                    purple_conversation_manager_seagull_backend_initable_iface_init))

static void
purple_conversation_manager_seagull_backend_finalize(GObject *obj) {
	PurpleConversationManagerSeagullBackend *backend = NULL;

	backend = PURPLE_CONVERSATION_MANAGER_SEAGULL_BACKEND(obj);

	g_clear_pointer(&backend->filename, g_free);

	g_clear_object(&backend->delete_properties);
	g_clear_object(&backend->delete_tags);
	g_clear_object(&backend->insert_properties);
	g_clear_object(&backend->insert_tags);
	g_clear_object(&backend->query_properties);
	g_clear_object(&backend->query_tags);

	if(backend->db != NULL) {
		GError *error = NULL;

		seagull_db_close(backend->db, &error);
		if(error != NULL) {
			g_warning("failed to close database: %s", error->message);
			g_clear_error(&error);
		}
	}

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

static void
purple_conversation_manager_seagull_backend_get_property(GObject *obj,
                                                         guint param_id,
                                                         GValue *value,
                                                         GParamSpec *pspec)
{
	PurpleConversationManagerSeagullBackend *backend = NULL;

	backend = PURPLE_CONVERSATION_MANAGER_SEAGULL_BACKEND(obj);

	switch(param_id) {
	case PROP_FILENAME:
		g_value_set_string(value,
		                   purple_conversation_manager_seagull_backend_get_filename(backend));
		break;
	default:
		G_OBJECT_WARN_INVALID_PROPERTY_ID(obj, param_id, pspec);
		break;
	}
}

static void
purple_conversation_manager_seagull_backend_set_property(GObject *obj,
                                                         guint param_id,
                                                         const GValue *value,
                                                         GParamSpec *pspec)
{
	PurpleConversationManagerSeagullBackend *backend = NULL;

	backend = PURPLE_CONVERSATION_MANAGER_SEAGULL_BACKEND(obj);

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

static void
purple_conversation_manager_seagull_backend_init(G_GNUC_UNUSED PurpleConversationManagerSeagullBackend *backend) {
}

static void
purple_conversation_manager_seagull_backend_class_init(PurpleConversationManagerSeagullBackendClass *klass) {
	GObjectClass *obj_class = G_OBJECT_CLASS(klass);
	PurpleConversationManagerBackendClass *backend_class = NULL;

	obj_class->finalize = purple_conversation_manager_seagull_backend_finalize;
	obj_class->get_property =
		purple_conversation_manager_seagull_backend_get_property;
	obj_class->set_property =
		purple_conversation_manager_seagull_backend_set_property;

	backend_class = PURPLE_CONVERSATION_MANAGER_BACKEND_CLASS(klass);
	backend_class->delete_conversation_async =
		purple_conversation_manager_seagull_backend_delete_conversation_async;
	backend_class->delete_conversation_finish =
		purple_conversation_manager_seagull_backend_delete_conversation_finish;
	backend_class->load_conversations_async =
		purple_conversation_manager_seagull_backend_load_conversations_async;
	backend_class->load_conversations_finish =
		purple_conversation_manager_seagull_backend_load_conversations_finish;
	backend_class->save_conversation_async =
		purple_conversation_manager_seagull_backend_save_conversation_async;
	backend_class->save_conversation_finish =
		purple_conversation_manager_seagull_backend_save_conversation_finish;

	/**
	 * PurpleConversationManagerSeagullBackend:filename:
	 *
	 * The filename that the backend should save its contents to.
	 *
	 * If this is %NULL, an in memory database will be used.
	 *
	 * 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);


	g_object_class_install_properties(obj_class, N_PROPERTIES, properties);
}

/******************************************************************************
 * Public API
 *****************************************************************************/
PurpleConversationManagerBackend *
purple_conversation_manager_seagull_backend_new(const char *filename,
                                                GError **error)
{
	return g_initable_new(
		PURPLE_TYPE_CONVERSATION_MANAGER_SEAGULL_BACKEND,
		NULL,
		error,
		"filename", filename,
		NULL);
}

const char *
purple_conversation_manager_seagull_backend_get_filename(PurpleConversationManagerSeagullBackend *backend) {
	g_return_val_if_fail(PURPLE_IS_CONVERSATION_MANAGER_SEAGULL_BACKEND(backend),
	                     NULL);

	return backend->filename;
}
