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

#include "purpleaccountmanager.h"
#include "purpleaccountmanagerseagullbackend.h"
#include "purplebadgemanager.h"
#include "purplecore.h"

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

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

struct _PurpleContactManagerSeagullBackend {
	PurpleContactManagerBackend parent;

	char *filename;
	SeagullSqlite3 *db;

	SeagullStatement *delete_contact_badges;
	SeagullStatement *delete_contact_properties;
	SeagullStatement *delete_contact_tags;
	SeagullStatement *insert_contact_badges;
	SeagullStatement *insert_contact_properties;
	SeagullStatement *insert_contact_tags;
	SeagullStatement *query_contact_badges;
	SeagullStatement *query_contact_properties;
	SeagullStatement *query_contact_tags;
};

#define RESOURCE_PATH "/im/pidgin/libpurple/contact-manager-seagull-backend"

/******************************************************************************
 * Helpers
 *****************************************************************************/
static void
purple_contact_manager_seagull_backend_set_filename(PurpleContactManagerSeagullBackend *backend,
                                                    const char *filename)
{
	g_return_if_fail(PURPLE_IS_CONTACT_MANAGER_SEAGULL_BACKEND(backend));

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

/******************************************************************************
 * Delete Contact Implementation
 *****************************************************************************/
static gboolean
purple_contact_manager_seagull_backend_delete_contact_helper(SeagullStatement *statement,
                                                             const char *account_id,
                                                             const char *contact_id,
                                                             GError **error)
{
	GError *local_error = NULL;
	gboolean success = FALSE;

	g_return_val_if_fail(SEAGULL_IS_STATEMENT(statement), FALSE);
	g_return_val_if_fail(!birb_str_is_empty(account_id), FALSE);
	g_return_val_if_fail(!birb_str_is_empty(contact_id), FALSE);

	/* Clear any existing usage. */
	if(!seagull_statement_clear_bindings(statement, error)) {
		return FALSE;
	}

	if(!seagull_statement_reset(statement, error)) {
		return FALSE;
	}

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

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

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

		return FALSE;
	}

	return TRUE;
}

static void
purple_contact_manager_seagull_backend_delete_contact_async(PurpleContactManagerBackend *purple_backend,
                                                            PurpleContact *contact,
                                                            GCancellable *cancellable,
                                                            GAsyncReadyCallback callback,
                                                            gpointer data)
{
	PurpleAccount *account = NULL;
	PurpleContactManagerSeagullBackend *backend = NULL;
	GError *error = NULL;
	GTask *task = NULL;
	const char *account_id = NULL;
	const char *contact_id = NULL;
	gboolean success = FALSE;

	backend = PURPLE_CONTACT_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;
	}

	account = purple_contact_get_account(contact);
	account_id = purple_account_get_id(account);
	contact_id = purple_contact_info_get_id(PURPLE_CONTACT_INFO(contact));

	success = purple_contact_manager_seagull_backend_delete_contact_helper(backend->delete_contact_properties,
	                                                                       account_id,
	                                                                       contact_id,
	                                                                       &error);
	if(error != NULL || !success) {
		GError *db_error = NULL;

		g_task_return_error(task, error);

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

		g_clear_object(&task);

		return;
	}

	/* Delete the badges. */
	success = purple_contact_manager_seagull_backend_delete_contact_helper(backend->delete_contact_badges,
	                                                                       account_id,
	                                                                       contact_id,
	                                                                       &error);
	if(error != NULL || !success) {
		GError *db_error = NULL;

		g_task_return_error(task, error);

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

		g_clear_object(&task);

		return;
	}

	/* Delete the tags. */
	success = purple_contact_manager_seagull_backend_delete_contact_helper(backend->delete_contact_tags,
	                                                                       account_id,
	                                                                       contact_id,
	                                                                       &error);
	if(error != NULL || !success) {
		GError *db_error = NULL;

		g_task_return_error(task, error);

		if(!seagull_transaction_rollback(backend->db, &db_error)) {
			g_warning("failed to rollback transaction: %s", db_error->message);
			g_clear_error(&db_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_contact_manager_seagull_backend_delete_contact_finish(PurpleContactManagerBackend *backend,
                                                             GAsyncResult *result,
                                                             GError **error)
{
	g_return_val_if_fail(PURPLE_IS_CONTACT_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 Contacts Implementation
 *****************************************************************************/
static void
purple_contact_manager_seagull_backend_load_contact_badges(PurpleContactManagerSeagullBackend *backend,
                                                           PurpleContact *contact,
                                                           const char *account_id,
                                                           const char *contact_id,
                                                           GError **error)
{
	PurpleBadgeManager *manager = NULL;
	PurpleBadges *badges = NULL;
	GError *local_error = NULL;

	badges = purple_contact_info_get_badges(PURPLE_CONTACT_INFO(contact));

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

		return;
	}

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

		return;
	}

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

		return;
	}

	manager = purple_badge_manager_get_default();

	while(seagull_statement_step(backend->query_contact_badges, &local_error)) {
		PurpleBadge *badge = NULL;
		const char *badge_id = NULL;

		badge_id = seagull_statement_column_text(backend->query_contact_badges,
		                                         "badge_id", &local_error);

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

			return;
		}

		badge = purple_badge_manager_find(manager, badge_id);
		if(PURPLE_IS_BADGE(badge)) {
			purple_badges_add_badge(badges, badge);
		}
	}

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

static void
purple_contact_manager_seagull_backend_load_contact_tags(PurpleContactManagerSeagullBackend *backend,
                                                         PurpleContact *contact,
                                                         const char *account_id,
                                                         const char *contact_id,
                                                         GError **error)
{
	PurpleTags *tags = NULL;
	GError *local_error = NULL;

	tags = purple_contact_info_get_tags(PURPLE_CONTACT_INFO(contact));

	purple_tags_remove_all(tags);

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

		return;
	}

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

		return;
	}

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

		return;
	}

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

		tag = seagull_statement_column_text(backend->query_contact_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_contact_manager_seagull_backend_load_contacts_async(PurpleContactManagerBackend *purple_backend,
                                                           GCancellable *cancellable,
                                                           GAsyncReadyCallback callback,
                                                           gpointer data)
{
	PurpleContactManagerSeagullBackend *backend = NULL;
	PurpleAccountManager *manager = NULL;
	PurpleContacts *contacts = NULL;
	GError *error = NULL;
	GTask *task = NULL;
	gboolean testing = FALSE;

	testing = g_test_initialized();

	backend = PURPLE_CONTACT_MANAGER_SEAGULL_BACKEND(purple_backend);

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

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

		g_clear_object(&task);

		return;
	}

	/* Core is null during the unit tests. */
	if(testing) {
		PurpleAccountManagerBackend *backend = NULL;

		backend = purple_account_manager_seagull_backend_new(":memory:", NULL);
		manager = g_object_new(PURPLE_TYPE_ACCOUNT_MANAGER,
		                       "backend", backend,
		                       NULL);
		g_clear_object(&backend);
	} else {
		PurpleCore *core = NULL;

		core = purple_core_get_default();
		manager = purple_core_get_account_manager(core);
	}


	contacts = purple_contacts_new();
	while(seagull_statement_step(backend->query_contact_properties, &error)) {
		PurpleAccount *account = NULL;
		PurpleContact *contact = NULL;
		PurplePresence *presence = NULL;
		const char *account_id = NULL;
		const char *contact_id = NULL;

		/* Grab the account id so we can find the account. */
		account_id = seagull_statement_column_text(backend->query_contact_properties,
		                                           "_account_id", &error);
		if(error != NULL) {
			g_warning("failed to read the account id: %s", error->message);

			g_clear_error(&error);

			continue;
		}

		/* If we're in a unit test we just create the account. */
		if(testing) {
			account = g_object_new(PURPLE_TYPE_ACCOUNT,
			                       "id", account_id,
			                       NULL);
		} else {
			account = purple_account_manager_find_by_id(manager, account_id);
			if(!PURPLE_IS_ACCOUNT(account)) {
				g_warning("failed to find an account with id %s", account_id);

				continue;
			}
		}

		/* Grab the contact id. */
		contact_id = seagull_statement_column_text(backend->query_contact_properties,
		                                           "_contact_id", &error);
		if(error != NULL) {
			g_warning("failed to read the contact id: %s", error->message);

			g_clear_error(&error);

			continue;
		}

		/* We have all the construct only properties, so let's create the
		 * instance.
		 */
		contact = purple_contact_new(account, contact_id);

		/* If we're in a unit test we need to remove our reference to the
		 * account.
		 */
		if(testing) {
			g_clear_object(&account);
		}

		/* Now set the rest of the properties. */
		seagull_statement_column_object(backend->query_contact_properties,
		                                NULL, G_OBJECT(contact), &error);

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

			g_clear_object(&contact);

			continue;
		}

		/* Get the presence. */
		presence = purple_contact_info_get_presence(PURPLE_CONTACT_INFO(contact));
		seagull_statement_column_object(backend->query_contact_properties,
		                                "presence_", G_OBJECT(presence),
		                                &error);

		if(error != NULL) {
			g_warning("failed to read contact presence for %s: %s",
			          contact_id,
			          error->message);
			g_clear_error(&error);

			g_clear_object(&contact);

			continue;
		}

		/* Load the badges. */
		purple_contact_manager_seagull_backend_load_contact_badges(backend,
		                                                           contact,
		                                                           account_id,
		                                                           contact_id,
		                                                           &error);
		if(error != NULL) {
			g_warning("failed to read contact badges for %s: %s",
			          contact_id,
			          error->message);
			g_clear_object(&error);

			g_clear_object(&contact);
			continue;
		}

		/* Load the tags. */
		purple_contact_manager_seagull_backend_load_contact_tags(backend,
		                                                         contact,
		                                                         account_id,
		                                                         contact_id,
		                                                         &error);
		if(error != NULL) {
			g_warning("failed to read contact tags for %s: %s",
			          contact_id,
			          error->message);
			g_clear_object(&error);

			g_clear_object(&contact);
			continue;
		}

		/* Add the contact to the collection. */
		purple_contacts_add(contacts, contact);

		g_clear_object(&contact);
	}

	if(testing) {
		g_clear_object(&manager);
	}

	if(error != NULL) {
		g_task_return_error(task, error);

		g_clear_object(&contacts);
	} else {
		g_task_return_pointer(task, contacts, g_object_unref);
	}

	g_clear_object(&task);
}

static PurpleContacts *
purple_contact_manager_seagull_backend_load_contacts_finish(PurpleContactManagerBackend *backend,
                                                            GAsyncResult *result,
                                                            GError **error)
{
	g_return_val_if_fail(PURPLE_IS_CONTACT_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 Contact Implementation
 *****************************************************************************/
static gboolean
purple_contact_manager_seagull_backend_save_contact_properties(PurpleContactManagerSeagullBackend *backend,
                                                               PurpleContact *contact,
                                                               GError **error)
{
	PurpleAccount *account = NULL;
	PurpleContactInfo *info = NULL;
	PurplePresence *presence = NULL;
	gboolean success = FALSE;

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

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

	/* Bind the properties for the contact. */
	account = purple_contact_get_account(contact);
	success = seagull_statement_bind_text(backend->insert_contact_properties,
	                                      ":_account_id",
	                                      purple_account_get_id(account),
	                                      -1, NULL, error);
	if(!success) {
		return FALSE;
	}

	info = PURPLE_CONTACT_INFO(contact);
	success = seagull_statement_bind_text(backend->insert_contact_properties,
	                                      ":_contact_id",
	                                      purple_contact_info_get_id(info),
	                                      -1, NULL, error);
	if(!success) {
		return FALSE;
	}

	success = seagull_statement_bind_object(backend->insert_contact_properties,
	                                        NULL, G_OBJECT(contact),
	                                        error);
	if(!success) {
		return FALSE;
	}

	presence = purple_contact_info_get_presence(info);
	success = seagull_statement_bind_object(backend->insert_contact_properties,
	                                        "presence_", G_OBJECT(presence),
	                                        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_contact_properties, error);
	if(error != NULL && *error != NULL) {
		return FALSE;
	}

	return TRUE;
}

static gboolean
purple_contact_manager_seagull_backend_save_contact_badges(PurpleContactManagerSeagullBackend *backend,
                                                           PurpleContact *contact,
                                                           GError **error)
{
	PurpleAccount *account = NULL;
	PurpleBadges *badges = NULL;
	GListModel *model = NULL;
	gboolean success = FALSE;
	const char *account_id = NULL;
	const char *contact_id = NULL;
	guint n_items = 0;

	account = purple_contact_get_account(contact);
	account_id = purple_account_get_id(account);
	contact_id = purple_contact_info_get_id(PURPLE_CONTACT_INFO(contact));

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

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

	/* Delete any old badges. */
	if(!purple_contact_manager_seagull_backend_delete_contact_helper(backend->delete_contact_badges,
	                                                                 account_id,
	                                                                 contact_id,
	                                                                 error))
	{
		return FALSE;
	}

	/* Bind the properties for the contact. */
	success = seagull_statement_bind_text(backend->insert_contact_badges,
	                                      ":account_id", account_id, -1,
	                                      NULL, error);
	if(!success) {
		return FALSE;
	}

	success = seagull_statement_bind_text(backend->insert_contact_badges,
	                                      ":contact_id", contact_id, -1,
	                                      NULL, error);
	if(!success) {
		return FALSE;
	}

	/* Now save all of the badges. */
	badges = purple_contact_info_get_badges(PURPLE_CONTACT_INFO(contact));
	model = G_LIST_MODEL(badges);
	n_items = g_list_model_get_n_items(model);
	for(guint i = 0; i < n_items; i++) {
		PurpleBadge *badge = NULL;

		badge = g_list_model_get_item(model, i);

		success = seagull_statement_bind_text(backend->insert_contact_badges,
		                                      ":badge_id",
		                                      purple_badge_get_id(badge),
		                                      -1,
		                                      NULL,
		                                      error);
		g_clear_object(&badge);

		if(!success) {
			return FALSE;
		}

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

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

			return FALSE;
		}

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

	return TRUE;
}

static gboolean
purple_contact_manager_seagull_backend_save_contact_tags(PurpleContactManagerSeagullBackend *backend,
                                                         PurpleContact *contact,
                                                         GError **error)
{
	PurpleAccount *account = NULL;
	PurpleTags *tags = NULL;
	GListModel *model = NULL;
	gboolean success = FALSE;
	const char *account_id = NULL;
	const char *contact_id = NULL;
	guint n_items = 0;

	account = purple_contact_get_account(contact);
	account_id = purple_account_get_id(account);
	contact_id = purple_contact_info_get_id(PURPLE_CONTACT_INFO(contact));

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

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

	/* Delete any olds tags. */
	if(!purple_contact_manager_seagull_backend_delete_contact_helper(backend->delete_contact_tags,
	                                                                 account_id,
	                                                                 contact_id,
	                                                                 error))
	{
		return FALSE;
	}

	/* Bind the properties for the contact. */
	success = seagull_statement_bind_text(backend->insert_contact_tags,
	                                      ":account_id", account_id, -1,
	                                      NULL, error);
	if(!success) {
		return FALSE;
	}

	success = seagull_statement_bind_text(backend->insert_contact_tags,
	                                      ":contact_id", contact_id, -1,
	                                      NULL, error);
	if(!success) {
		return FALSE;
	}

	/* Now save all of the tags. */
	tags = purple_contact_info_get_tags(PURPLE_CONTACT_INFO(contact));
	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_contact_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_contact_tags, error);
		if(error != NULL && *error != NULL) {
			char *expanded = NULL;

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

			return FALSE;
		}

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

	return TRUE;
}

static void
purple_contact_manager_seagull_backend_save_contact_async(PurpleContactManagerBackend *purple_backend,
                                                          PurpleContact *contact,
                                                          GCancellable *cancellable,
                                                          GAsyncReadyCallback callback,
                                                          gpointer data)
{
	PurpleContactManagerSeagullBackend *backend = NULL;
	GError *error = NULL;
	GTask *task = NULL;
	gboolean success = FALSE;

	backend = PURPLE_CONTACT_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 properties. */
	success = purple_contact_manager_seagull_backend_save_contact_properties(backend,
	                                                                         contact,
	                                                                         &error);
	if(!success) {
		GError *db_error = NULL;

		g_task_return_error(task, error);

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

		g_clear_object(&task);

		return;
	}

	/* Save the badges. */
	success = purple_contact_manager_seagull_backend_save_contact_badges(backend,
	                                                                     contact,
	                                                                     &error);
	if(!success) {
		GError *db_error = NULL;

		g_task_return_error(task, error);

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

		g_clear_object(&task);

		return;
	}

	/* Save the tags. */
	success = purple_contact_manager_seagull_backend_save_contact_tags(backend,
	                                                                   contact,
	                                                                   &error);
	if(!success) {
		GError *db_error = NULL;

		g_task_return_error(task, error);

		if(!seagull_transaction_rollback(backend->db, &db_error)) {
			g_warning("failed to rollback transaction: %s", db_error->message);
			g_clear_error(&db_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_contact_manager_seagull_backend_save_contact_finish(PurpleContactManagerBackend *backend,
                                                           GAsyncResult *result,
                                                           GError **error)
{
	g_return_val_if_fail(PURPLE_IS_CONTACT_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_contact_manager_seagull_backend_initable_init(GInitable *initable,
                                                     G_GNUC_UNUSED GCancellable *cancellable,
                                                     GError **error)
{
	PurpleContactManagerSeagullBackend *backend = NULL;
	SeagullStatement *stmt = NULL;
	GError *local_error = NULL;
	gboolean result = FALSE;
	const char *migrations[] = {
		"01-initial.sql",
		"02-presence.sql",
		"03-created-time.sql",
		NULL
	};

	backend = PURPLE_CONTACT_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;
	}

	/* Load the badges statements. */
	stmt = seagull_statement_new_from_resource(backend->db,
	                                           RESOURCE_PATH "/statements/delete-contact-badges.sql",
	                                           &local_error);
	if(local_error != NULL) {
		g_propagate_prefixed_error(error, local_error,
		                           "delete-contact-badges: ");

		return FALSE;
	}
	backend->delete_contact_badges = stmt;

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

		return FALSE;
	}
	backend->insert_contact_badges = stmt;

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

		return FALSE;
	}
	backend->query_contact_badges = stmt;

	/* Load the properties statements. */
	stmt = seagull_statement_new_from_resource(backend->db,
	                                           RESOURCE_PATH "/statements/delete-contact-properties.sql",
	                                           &local_error);
	if(local_error != NULL) {
		g_propagate_prefixed_error(error, local_error,
		                           "delete-contact-properties: ");

		return FALSE;
	}
	backend->delete_contact_properties = stmt;

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

		return FALSE;
	}
	backend->insert_contact_properties = stmt;

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

		return FALSE;
	}
	backend->query_contact_properties = stmt;

	/* Load the tags statements. */
	stmt = seagull_statement_new_from_resource(backend->db,
	                                           RESOURCE_PATH "/statements/delete-contact-tags.sql",
	                                           &local_error);
	if(local_error != NULL) {
		g_propagate_prefixed_error(error, local_error,
		                           "delete-contact-tags: ");

		return FALSE;
	}
	backend->delete_contact_tags = stmt;

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

		return FALSE;
	}
	backend->insert_contact_tags = stmt;

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

		return FALSE;
	}
	backend->query_contact_tags = stmt;

	return TRUE;
}

static void
purple_contact_manager_seagull_backend_initable_iface_init(GInitableIface *iface)
{
	iface->init = purple_contact_manager_seagull_backend_initable_init;
}

/******************************************************************************
 * GObject Implementation
 *****************************************************************************/
G_DEFINE_FINAL_TYPE_WITH_CODE(PurpleContactManagerSeagullBackend,
                              purple_contact_manager_seagull_backend,
                              PURPLE_TYPE_CONTACT_MANAGER_BACKEND,
                              G_IMPLEMENT_INTERFACE(G_TYPE_INITABLE,
                                                    purple_contact_manager_seagull_backend_initable_iface_init))

static void
purple_contact_manager_seagull_backend_finalize(GObject *obj) {
	PurpleContactManagerSeagullBackend *backend = NULL;

	backend = PURPLE_CONTACT_MANAGER_SEAGULL_BACKEND(obj);

	g_clear_pointer(&backend->filename, g_free);

	g_clear_object(&backend->delete_contact_badges);
	g_clear_object(&backend->delete_contact_properties);
	g_clear_object(&backend->delete_contact_tags);
	g_clear_object(&backend->insert_contact_badges);
	g_clear_object(&backend->insert_contact_properties);
	g_clear_object(&backend->insert_contact_tags);
	g_clear_object(&backend->query_contact_badges);
	g_clear_object(&backend->query_contact_properties);
	g_clear_object(&backend->query_contact_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_contact_manager_seagull_backend_parent_class)->finalize(obj);
}

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

	backend = PURPLE_CONTACT_MANAGER_SEAGULL_BACKEND(obj);

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

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

	backend = PURPLE_CONTACT_MANAGER_SEAGULL_BACKEND(obj);

	switch(param_id) {
	case PROP_FILENAME:
		purple_contact_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_contact_manager_seagull_backend_init(G_GNUC_UNUSED PurpleContactManagerSeagullBackend *backend) {
}

static void
purple_contact_manager_seagull_backend_class_init(PurpleContactManagerSeagullBackendClass *klass) {
	GObjectClass *obj_class = G_OBJECT_CLASS(klass);
	PurpleContactManagerBackendClass *backend_class = NULL;

	obj_class->finalize = purple_contact_manager_seagull_backend_finalize;
	obj_class->get_property =
		purple_contact_manager_seagull_backend_get_property;
	obj_class->set_property =
		purple_contact_manager_seagull_backend_set_property;

	backend_class = PURPLE_CONTACT_MANAGER_BACKEND_CLASS(klass);
	backend_class->delete_contact_async =
		purple_contact_manager_seagull_backend_delete_contact_async;
	backend_class->delete_contact_finish =
		purple_contact_manager_seagull_backend_delete_contact_finish;
	backend_class->load_contacts_async =
		purple_contact_manager_seagull_backend_load_contacts_async;
	backend_class->load_contacts_finish =
		purple_contact_manager_seagull_backend_load_contacts_finish;
	backend_class->save_contact_async =
		purple_contact_manager_seagull_backend_save_contact_async;
	backend_class->save_contact_finish =
		purple_contact_manager_seagull_backend_save_contact_finish;

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


	g_object_class_install_properties(obj_class, N_PROPERTIES, properties);
}

/******************************************************************************
 * Public API
 *****************************************************************************/
PurpleContactManagerBackend *
purple_contact_manager_seagull_backend_new(const char *filename,
                                           GError **error)
{
	return g_initable_new(
		PURPLE_TYPE_CONTACT_MANAGER_SEAGULL_BACKEND,
		NULL,
		error,
		"filename", filename,
		NULL);
}

const char *
purple_contact_manager_seagull_backend_get_filename(PurpleContactManagerSeagullBackend *backend) {
	g_return_val_if_fail(PURPLE_IS_CONTACT_MANAGER_SEAGULL_BACKEND(backend),
	                     NULL);

	return backend->filename;
}
