/*
 * Purple - Internet Messaging Library
 * Copyright (C) Pidgin Developers <devel@pidgin.im>
 *
 * Purple is the legal property of its developers, whose names are too numerous
 * to list here. Please refer to the COPYRIGHT file distributed with this
 * source distribution.
 *
 * This library is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this library; if not, see <https://www.gnu.org/licenses/>.
 */

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

#include "purpleaccountmanagerseagullbackend.h"

#include "purpleaccountsettingstringlist.h"
#include "purplebadgemanager.h"

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

struct _PurpleAccountManagerSeagullBackend {
	PurpleAccountManagerBackend parent;

	char *filename;
	SeagullSqlite3 *db;

	SeagullStatement *delete_contact_info_badges;
	SeagullStatement *delete_contact_info_tags;
	SeagullStatement *delete_properties;
	SeagullStatement *delete_settings;
	SeagullStatement *insert_contact_info_badges;
	SeagullStatement *insert_contact_info_tags;
	SeagullStatement *insert_properties;
	SeagullStatement *insert_settings;
	SeagullStatement *query_contact_info_badges;
	SeagullStatement *query_contact_info_tags;
	SeagullStatement *query_properties;
	SeagullStatement *query_settings;
};

G_DEFINE_QUARK(purple-account-manager-seagull-backend-error,
               purple_account_manager_seagull_backend_error)

#define RESOURCE_PATH "/im/pidgin/libpurple/account-manager-seagull-backend"
#define STATEMENTS_PATH RESOURCE_PATH "/statements"

/******************************************************************************
 * Helpers
 *****************************************************************************/
static void
purple_account_manager_seagull_backend_set_filename(PurpleAccountManagerSeagullBackend *backend,
                                                    const char *filename)
{
	if(g_set_str(&backend->filename, filename)) {
		g_object_notify_by_pspec(G_OBJECT(backend), properties[PROP_FILENAME]);
	}
}

/******************************************************************************
 * Delete Account Implementation
 *****************************************************************************/
static gboolean
purple_account_manager_seagull_backend_delete_account_helper(SeagullStatement *statement,
                                                             const char *parameter_name,
                                                             const char *account_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);

	/* 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,
	                                      parameter_name, account_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_account_manager_seagull_backend_delete_account_async(PurpleAccountManagerBackend *purple_backend,
                                                            PurpleAccount *account,
                                                            GCancellable *cancellable,
                                                            GAsyncReadyCallback callback,
                                                            gpointer data)
{
	PurpleAccountManagerSeagullBackend *backend = NULL;
	GError *error = NULL;
	GTask *task = NULL;
	const char *account_id = NULL;
	gboolean success = FALSE;

	backend = PURPLE_ACCOUNT_MANAGER_SEAGULL_BACKEND(purple_backend);

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

	/* 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_id = purple_account_get_id(account);

	/* Delete the contact info badges. */
	success = purple_account_manager_seagull_backend_delete_account_helper(backend->delete_contact_info_badges,
	                                                                       ":account_id",
	                                                                       account_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 contact info tags. */
	success = purple_account_manager_seagull_backend_delete_account_helper(backend->delete_contact_info_tags,
	                                                                       ":account_id",
	                                                                       account_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 properties. */
	success = purple_account_manager_seagull_backend_delete_account_helper(backend->delete_properties,
	                                                                       ":id",
	                                                                       account_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 settings. */
	success = purple_account_manager_seagull_backend_delete_account_helper(backend->delete_settings,
	                                                                       ":account_id",
	                                                                       account_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_account_manager_seagull_backend_delete_account_finish(PurpleAccountManagerBackend *backend,
                                                             GAsyncResult *result,
                                                             GError **error)
{
	g_return_val_if_fail(PURPLE_IS_ACCOUNT_MANAGER_SEAGULL_BACKEND(backend),
	                     FALSE);
	g_return_val_if_fail(g_task_is_valid(G_TASK(result), backend), FALSE);

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

/******************************************************************************
 * Load Accounts Implementation
 *****************************************************************************/
static void
purple_account_manager_seagull_backend_load_contact_info_badges(PurpleAccountManagerSeagullBackend *backend,
                                                                PurpleContactInfo *info,
                                                                const char *account_id,
                                                                GError **error)
{
	PurpleBadgeManager *manager = NULL;
	PurpleBadges *badges = NULL;
	GError *local_error = NULL;

	badges = purple_contact_info_get_badges(info);

	/* Reset the statement. */
	seagull_statement_reset(backend->query_contact_info_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_info_badges,
	                            ":account_id", account_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_info_badges,
	      &local_error))
	{
		PurpleBadge *badge = NULL;
		const char *badge_id = NULL;

		badge_id = seagull_statement_column_text(backend->query_contact_info_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_account_manager_seagull_backend_load_contact_info_tags(PurpleAccountManagerSeagullBackend *backend,
                                                              PurpleContactInfo *info,
                                                              const char *account_id,
                                                              GError **error)
{
	PurpleTags *tags = NULL;
	GError *local_error = NULL;

	tags = purple_contact_info_get_tags(info);

	purple_tags_remove_all(tags);

	/* Reset the statement. */
	seagull_statement_reset(backend->query_contact_info_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_info_tags, ":account_id",
	                            account_id, -1, NULL, &local_error);
	if(local_error != NULL) {
		g_propagate_error(error, local_error);

		return;
	}

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

		tag = seagull_statement_column_text(backend->query_contact_info_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_account_manager_seagull_backend_load_settings(PurpleAccountManagerSeagullBackend *backend,
                                                     PurpleAccount *account,
                                                     const char *account_id,
                                                     GError **error)
{
	PurpleAccountSettings *settings = NULL;
	PurpleProtocol *protocol = NULL;
	GError *local_error = NULL;

	settings = purple_account_get_settings(account);

	/* Blank out the settings. */
	purple_account_settings_remove_all_settings(settings);

	/* Load the default settings from the protocol if we have one. */
	protocol = purple_account_get_protocol(account);
	if(PURPLE_IS_PROTOCOL(properties)) {
		PurpleAccountSettings *default_settings = NULL;

		default_settings = purple_protocol_get_default_account_settings(protocol);
		if(PURPLE_IS_ACCOUNT_SETTINGS(default_settings)) {
			purple_account_settings_update_settings(settings,
			                                        default_settings);
		}
		g_clear_object(&default_settings);
	}

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

		return;
	}

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

		return;
	}

	while(seagull_statement_step(backend->query_settings, &local_error)) {
		PurpleAccountSetting *setting = NULL;
		GType g_type = G_TYPE_INVALID;
		const char *id = NULL;
		const char *type_name = NULL;

		/* Look up the type name first to make sure it exists. */
		type_name = seagull_statement_column_text(backend->query_settings,
		                                          "_type", &local_error);
		if(local_error != NULL) {
			g_warning("failed to read the type name of the setting: %s",
			          local_error->message);

			g_clear_error(&local_error);

			continue;
		}

		g_type = g_type_from_name(type_name);
		if(g_type == G_TYPE_INVALID) {
			g_warning("failed to find a type with name %s", type_name);

			continue;
		}

		if(!g_type_is_a(g_type, PURPLE_TYPE_ACCOUNT_SETTING)) {
			g_warning("type %s is not an account setting", type_name);

			continue;
		}

		/* Now grab the id of the setting. */
		id = seagull_statement_column_text(backend->query_settings, "_id",
		                                   &local_error);
		if(local_error != NULL) {
			g_warning("failed to get the id of the setting: %s",
			          local_error->message);

			g_clear_error(&local_error);

			continue;
		}

		setting = g_object_new(g_type, "id", id, NULL);

		/* Special case PurpleAccountSettingStringList. */
		if(PURPLE_IS_ACCOUNT_SETTING_STRING_LIST(setting)) {
			const char *active_item = NULL;

			active_item = seagull_statement_column_text(backend->query_settings,
			                                            "value", &local_error);

			if(local_error != NULL) {
				g_warning("failed to get the active item for %s: %s",
				          id, local_error->message);

				g_clear_error(&local_error);
				g_clear_object(&setting);

				continue;
			}

			purple_account_setting_string_list_set_active_item(PURPLE_ACCOUNT_SETTING_STRING_LIST(setting),
			                                                   active_item);
		} else {
			seagull_statement_column_object(backend->query_settings, NULL,
			                                G_OBJECT(setting), &local_error);
			if(local_error != NULL) {
				g_warning("failed to read the properties of setting %s for account "
				          "%s: %s",
				          id, account_id, local_error->message);

				g_clear_error(&local_error);
				g_clear_object(&setting);

				continue;
			}
		}

		purple_account_settings_add_setting(settings, setting);
	}

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

static void
purple_account_manager_seagull_backend_load_accounts_async(PurpleAccountManagerBackend *purple_backend,
                                                           GCancellable *cancellable,
                                                           GAsyncReadyCallback callback,
                                                           gpointer data)
{
	PurpleAccountManagerSeagullBackend *backend = NULL;
	GError *error = NULL;
	GListStore *accounts = NULL;
	GTask *task = NULL;
	gboolean success = FALSE;

	backend = PURPLE_ACCOUNT_MANAGER_SEAGULL_BACKEND(purple_backend);

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

	/* Reset our prepared statement. */
	success = seagull_statement_reset(backend->query_properties, &error);
	if(error != NULL) {
		g_task_return_error(task, error);

		g_clear_object(&task);

		return;
	}

	if(!success) {
		g_task_return_new_error_literal(task,
		                                PURPLE_ACCOUNT_MANAGER_SEAGULL_BACKEND_ERROR,
		                                PURPLE_ACCOUNT_MANAGER_SEAGULL_BACKEND_ERROR_FAILED_TO_CLEANUP,
		                                "failed to reset the query account "
		                                "properties statement");

		g_clear_object(&task);

		return;
	}

	/* Clear any existing bindings. */
	success = seagull_statement_clear_bindings(backend->query_properties,
	                                           &error);
	if(error != NULL) {
		g_task_return_error(task, error);

		g_clear_object(&task);

		return;
	}

	if(!success) {
		g_task_return_new_error_literal(task,
		                                PURPLE_ACCOUNT_MANAGER_SEAGULL_BACKEND_ERROR,
		                                PURPLE_ACCOUNT_MANAGER_SEAGULL_BACKEND_ERROR_FAILED_TO_CLEANUP,
		                                "failed to clear bindings for the "
		                                "query account properties statement");

		g_clear_object(&task);

		return;
	}

	accounts = g_list_store_new(PURPLE_TYPE_ACCOUNT);

	while(seagull_statement_step(backend->query_properties, &error)) {
		PurpleAccount *account = NULL;
		PurpleContactInfo *info = NULL;
		const char *account_id = NULL;

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

			g_clear_error(&error);

			continue;
		}

		account = g_object_new(
			PURPLE_TYPE_ACCOUNT,
			"id", account_id,
			NULL);

		/* Now load the rest of the properties for the account. */
		seagull_statement_column_object(backend->query_properties, NULL,
		                                G_OBJECT(account), &error);

		if(error != NULL) {
			g_warning("failed to load properties for account %s: %s",
			          account_id, error->message);

			g_clear_error(&error);
			g_clear_object(&account);

			continue;
		}

		/* And now the contact info properties. */
		info = purple_account_get_contact_info(account);
		seagull_statement_column_object(backend->query_properties,
		                                "contact_info_", G_OBJECT(info),
		                                &error);

		if(error != NULL) {
			g_warning("failed to load contact info properties for account %s: "
			          "%s",
			          account_id, error->message);

			g_clear_error(&error);
			g_clear_object(&account);

			continue;
		}

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

			g_clear_object(&error);
			g_clear_object(&account);

			continue;
		}

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

			g_clear_object(&error);
			g_clear_object(&account);

			continue;
		}

		/* Load the settings. */
		purple_account_manager_seagull_backend_load_settings(backend, account,
		                                                     account_id,
		                                                     &error);
		if(error != NULL) {
			g_warning("failed to read account settings for %s: %s",
			          account_id,
			          error->message);

			g_clear_object(&error);
			g_clear_object(&account);

			continue;
		}

		/* Add the account to the collection. */
		g_list_store_append(accounts, account);

		g_clear_object(&account);
	}

	g_task_return_pointer(task, accounts, g_object_unref);

	g_clear_object(&task);
}

static GListModel *
purple_account_manager_seagull_backend_load_accounts_finish(PurpleAccountManagerBackend *backend,
                                                            GAsyncResult *result,
                                                            GError **error)
{
	g_return_val_if_fail(PURPLE_IS_ACCOUNT_MANAGER_SEAGULL_BACKEND(backend),
	                     NULL);
	g_return_val_if_fail(g_task_is_valid(G_TASK(result), backend), NULL);

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

/******************************************************************************
 * Save Account Implementation
 *****************************************************************************/
static gboolean
purple_account_manager_seagull_backend_save_contact_info_badges(PurpleAccountManagerSeagullBackend *backend,
                                                                PurpleAccount *account,
                                                                GError **error)
{
	PurpleBadges *badges = NULL;
	PurpleContactInfo *info = NULL;
	gboolean success = FALSE;
	const char *account_id = NULL;
	guint n_items = 0;

	account_id = purple_account_get_id(account);
	info = purple_account_get_contact_info(account);

	/* Delete any old badges. */
	if(!purple_account_manager_seagull_backend_delete_account_helper(backend->delete_contact_info_badges,
	                                                                 ":account_id",
	                                                                 account_id,
	                                                                 error))
	{
		return FALSE;
	}

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

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

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

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

		badge = g_list_model_get_item(G_LIST_MODEL(badges), i);

		success = seagull_statement_bind_text(backend->insert_contact_info_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_info_badges, error);
		if(error != NULL && *error != NULL) {
			char *expanded = NULL;

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

			return FALSE;
		}

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

	return TRUE;
}

static gboolean
purple_account_manager_seagull_backend_save_contact_info_tags(PurpleAccountManagerSeagullBackend *backend,
                                                              PurpleAccount *account,
                                                              GError **error)
{
	PurpleContactInfo *info = NULL;
	PurpleTags *tags = NULL;
	gboolean success = FALSE;
	const char *account_id = NULL;
	guint n_items = 0;

	account_id = purple_account_get_id(account);
	info = purple_account_get_contact_info(account);

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

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

	/* Delete any olds tags. */
	if(!purple_account_manager_seagull_backend_delete_account_helper(backend->delete_contact_info_tags,
	                                                                 ":account_id",
	                                                                 account_id,
	                                                                 error))
	{
		return FALSE;
	}

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

	/* Now save all of the tags. */
	tags = purple_contact_info_get_tags(info);
	n_items = g_list_model_get_n_items(G_LIST_MODEL(tags));
	for(guint i = 0; i < n_items; i++) {
		BirbStringObject *obj = NULL;
		const char *tag = NULL;

		obj = g_list_model_get_item(G_LIST_MODEL(tags), i);
		tag = birb_string_object_get_string(obj);

		success = seagull_statement_bind_text(backend->insert_contact_info_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_info_tags, error);
		if(error != NULL && *error != NULL) {
			char *expanded = NULL;

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

			return FALSE;
		}

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

	return TRUE;
}

static gboolean
purple_account_manager_seagull_backend_save_properties(PurpleAccountManagerSeagullBackend *backend,
                                                       PurpleAccount *account,
                                                       GError **error)
{
	PurpleContactInfo *info = NULL;
	gboolean success = FALSE;

	info = purple_account_get_contact_info(account);

	/* 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 account to the statement. */
	success = seagull_statement_bind_object(backend->insert_properties,
	                                        NULL, G_OBJECT(account),
	                                        error);
	if(!success) {
		return FALSE;
	}

	/* Bind the contact-info to the statement. */
	success = seagull_statement_bind_object(backend->insert_properties,
	                                        "contact_info_", G_OBJECT(info),
	                                        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) {
		return FALSE;
	}

	return TRUE;
}

static gboolean
purple_account_manager_seagull_backend_save_settings(PurpleAccountManagerSeagullBackend *backend,
                                                     PurpleAccount *account,
                                                     GError **error)
{
	PurpleAccountSettings *settings = NULL;
	gboolean success = FALSE;
	const char *account_id = NULL;
	guint n_items = 0;

	account_id = purple_account_get_id(account);
	settings = purple_account_get_settings(account);

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

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

	/* Delete any old settings. */
	if(!purple_account_manager_seagull_backend_delete_account_helper(backend->delete_settings,
	                                                                 ":account_id",
	                                                                 account_id,
	                                                                 error))
	{
		return FALSE;
	}

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

	/* Now save all of the settings. */
	n_items = g_list_model_get_n_items(G_LIST_MODEL(settings));
	for(guint i = 0; i < n_items; i++) {
		PurpleAccountSetting *setting = NULL;
		const char *type_name = NULL;

		setting = g_list_model_get_item(G_LIST_MODEL(settings), i);

		success = seagull_statement_bind_object(backend->insert_settings, NULL,
		                                        G_OBJECT(setting), error);
		if(!success) {
			g_clear_object(&setting);

			return FALSE;
		}

		/* Special case PurpleAccountSettingStringList. */
		if(PURPLE_IS_ACCOUNT_SETTING_STRING_LIST(setting)) {
			const char *active_item = NULL;

			active_item = purple_account_setting_string_list_get_active_item(PURPLE_ACCOUNT_SETTING_STRING_LIST(setting));

			success = seagull_statement_bind_text(backend->insert_settings,
			                                      ":value", active_item, -1,
			                                      NULL, error);
			if(!success) {
				g_clear_object(&setting);

				return FALSE;
			}
		}

		type_name = G_OBJECT_TYPE_NAME(setting);
		success = seagull_statement_bind_text(backend->insert_settings,
		                                      ":type", type_name, -1, NULL,
		                                      error);
		if(!success) {
			g_clear_object(&setting);

			return FALSE;
		}

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

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

			return FALSE;
		}

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

	return TRUE;
}

static void
purple_account_manager_seagull_backend_save_account_async(PurpleAccountManagerBackend *backend,
                                                          PurpleAccount *account,
                                                          GCancellable *cancellable,
                                                          GAsyncReadyCallback callback,
                                                          gpointer data)
{
	PurpleAccountManagerSeagullBackend *seagull_backend = NULL;
	GError *error = NULL;
	GTask *task = NULL;

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

	seagull_backend = PURPLE_ACCOUNT_MANAGER_SEAGULL_BACKEND(backend);

	if(!purple_account_manager_seagull_backend_save_contact_info_badges(seagull_backend,
	                                                                    account,
	                                                                    &error))
	{
		g_task_return_error(task, error);
		g_clear_object(&task);

		return;
	}

	if(!purple_account_manager_seagull_backend_save_contact_info_tags(seagull_backend,
	                                                                  account,
	                                                                  &error))
	{
		g_task_return_error(task, error);
		g_clear_object(&task);

		return;
	}

	if(!purple_account_manager_seagull_backend_save_properties(seagull_backend,
	                                                           account,
	                                                           &error))
	{
		g_task_return_error(task, error);
		g_clear_object(&task);

		return;
	}

	if(!purple_account_manager_seagull_backend_save_settings(seagull_backend,
	                                                         account,
	                                                         &error))
	{
		g_task_return_error(task, error);
		g_clear_object(&task);

		return;
	}

	g_task_return_boolean(task, TRUE);
	g_clear_object(&task);
}

static gboolean
purple_account_manager_seagull_backend_save_account_finish(PurpleAccountManagerBackend *backend,
                                                           GAsyncResult *result,
                                                           GError **error)
{
	g_return_val_if_fail(PURPLE_IS_ACCOUNT_MANAGER_SEAGULL_BACKEND(backend),
	                     FALSE);
	g_return_val_if_fail(g_task_is_valid(G_TASK(result), backend), FALSE);

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

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

	backend = PURPLE_ACCOUNT_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_prefixed_error(error, local_error, "create-db:");

		return FALSE;
	}

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

	if(!result) {
		g_propagate_prefixed_error(error, local_error, "migrations:");

		return FALSE;
	}

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

		return FALSE;
	}
	backend->delete_contact_info_badges = stmt;

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

		return FALSE;
	}
	backend->insert_contact_info_badges = stmt;

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

		return FALSE;
	}
	backend->query_contact_info_badges = stmt;

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

		return FALSE;
	}
	backend->delete_contact_info_tags = stmt;

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

		return FALSE;
	}
	backend->insert_contact_info_tags = stmt;

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

		return FALSE;
	}
	backend->query_contact_info_tags = stmt;

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

		return FALSE;
	}
	backend->delete_properties = stmt;

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

		return FALSE;
	}
	backend->insert_properties = stmt;

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

		return FALSE;
	}
	backend->query_properties = stmt;

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

		return FALSE;
	}
	backend->delete_settings = stmt;

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

		return FALSE;
	}
	backend->insert_settings = stmt;

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

		return FALSE;
	}
	backend->query_settings = stmt;

	return TRUE;
}

static void
purple_account_manager_seagull_backend_initable_iface_init(GInitableIface *iface) {
	iface->init = purple_account_manager_seagull_backend_initable_init;
}

/******************************************************************************
 * GObject Implementation
 *****************************************************************************/
G_DEFINE_FINAL_TYPE_WITH_CODE(PurpleAccountManagerSeagullBackend,
                              purple_account_manager_seagull_backend,
                              PURPLE_TYPE_ACCOUNT_MANAGER_BACKEND,
                              G_IMPLEMENT_INTERFACE(G_TYPE_INITABLE,
                                                    purple_account_manager_seagull_backend_initable_iface_init))

static void
purple_account_manager_seagull_backend_finalize(GObject *obj) {
	PurpleAccountManagerSeagullBackend *backend = NULL;
	GError *error = NULL;

	backend = PURPLE_ACCOUNT_MANAGER_SEAGULL_BACKEND(obj);

	g_clear_pointer(&backend->filename, g_free);

	g_clear_object(&backend->delete_contact_info_badges);
	g_clear_object(&backend->delete_contact_info_tags);
	g_clear_object(&backend->delete_properties);
	g_clear_object(&backend->delete_settings);
	g_clear_object(&backend->insert_contact_info_badges);
	g_clear_object(&backend->insert_contact_info_tags);
	g_clear_object(&backend->insert_properties);
	g_clear_object(&backend->insert_settings);
	g_clear_object(&backend->query_contact_info_badges);
	g_clear_object(&backend->query_contact_info_tags);
	g_clear_object(&backend->query_properties);
	g_clear_object(&backend->query_settings);

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

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

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

	backend = PURPLE_ACCOUNT_MANAGER_SEAGULL_BACKEND(obj);

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

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

	backend = PURPLE_ACCOUNT_MANAGER_SEAGULL_BACKEND(obj);

	switch(param_id) {
	case PROP_FILENAME:
		purple_account_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_account_manager_seagull_backend_init(G_GNUC_UNUSED PurpleAccountManagerSeagullBackend *backend)
{
}

static void
purple_account_manager_seagull_backend_class_init(PurpleAccountManagerSeagullBackendClass *klass)
{
	GObjectClass *obj_class = G_OBJECT_CLASS(klass);
	PurpleAccountManagerBackendClass *backend_class = NULL;

	obj_class->finalize = purple_account_manager_seagull_backend_finalize;
	obj_class->get_property =
		purple_account_manager_seagull_backend_get_property;
	obj_class->set_property =
		purple_account_manager_seagull_backend_set_property;

	backend_class = PURPLE_ACCOUNT_MANAGER_BACKEND_CLASS(klass);
	backend_class->delete_account_async =
		purple_account_manager_seagull_backend_delete_account_async;
	backend_class->delete_account_finish =
		purple_account_manager_seagull_backend_delete_account_finish;
	backend_class->load_accounts_async =
		purple_account_manager_seagull_backend_load_accounts_async;
	backend_class->load_accounts_finish =
		purple_account_manager_seagull_backend_load_accounts_finish;
	backend_class->save_account_async =
		purple_account_manager_seagull_backend_save_account_async;
	backend_class->save_account_finish =
		purple_account_manager_seagull_backend_save_account_finish;

	/**
	 * PurpleAccountManagerSeagullBackend: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
 *****************************************************************************/
const char *
purple_account_manager_seagull_backend_get_filename(PurpleAccountManagerSeagullBackend *backend)
{
	g_return_val_if_fail(PURPLE_IS_ACCOUNT_MANAGER_SEAGULL_BACKEND(backend),
	                     NULL);

	return backend->filename;
}

PurpleAccountManagerBackend *
purple_account_manager_seagull_backend_new(const char *filename,
                                           GError **error)
{
	return g_initable_new(
		PURPLE_TYPE_ACCOUNT_MANAGER_SEAGULL_BACKEND,
		NULL,
		error,
		"filename", filename,
		NULL);
}
