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

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

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

struct _PurplePresenceManagerSeagullBackend {
	PurplePresenceManagerBackend parent;

	char *filename;
	SeagullSqlite3 *db;

	SeagullStatement *delete_properties;
	SeagullStatement *insert_properties;
	SeagullStatement *query_properties;
};

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

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

static void
purple_presence_manager_seagull_backend_set_filename(PurplePresenceManagerSeagullBackend *backend,
                                                     const char *filename)
{
	g_return_if_fail(PURPLE_IS_PRESENCE_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_presence_manager_seagull_backend_delete_saved_presence_properties(PurplePresenceManagerSeagullBackend *backend,
                                                                         const char *saved_presence_id,
                                                                         GError **error)
{
	GError *local_error = NULL;
	gboolean success = FALSE;

	g_return_val_if_fail(PURPLE_IS_PRESENCE_MANAGER_SEAGULL_BACKEND(backend),
	                     FALSE);
	g_return_val_if_fail(!birb_str_is_empty(saved_presence_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 saved_presence id to the delete statement. */
	success = seagull_statement_bind_text(backend->delete_properties,
	                                      ":id", saved_presence_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_presence_manager_seagull_backend_delete_saved_presence_async(PurplePresenceManagerBackend *purple_backend,
                                                                    PurpleSavedPresence *saved_presence,
                                                                    GCancellable *cancellable,
                                                                    GAsyncReadyCallback callback,
                                                                    gpointer data)
{
	PurplePresenceManagerSeagullBackend *backend = NULL;
	GError *error = NULL;
	GTask *task = NULL;
	const char *saved_presence_id = NULL;
	gboolean success = FALSE;

	backend = PURPLE_PRESENCE_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 _saved_presence and account ids as we need them for everything. */
	saved_presence_id = purple_saved_presence_get_id(saved_presence);

	success = purple_presence_manager_seagull_backend_delete_saved_presence_properties(backend,
	                                                                                   saved_presence_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_presence_manager_seagull_backend_delete_saved_presence_finish(PurplePresenceManagerBackend *backend,
                                                                     GAsyncResult *result,
                                                                     GError **error)
{
	g_return_val_if_fail(PURPLE_IS_PRESENCE_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_presence_manager_seagull_backend_load_saved_presences_async(PurplePresenceManagerBackend *purple_backend,
                                                                   GCancellable *cancellable,
                                                                   GAsyncReadyCallback callback,
                                                                   gpointer data)
{
	PurplePresenceManagerSeagullBackend *backend = NULL;
	GError *error = NULL;
	GListStore *saved_presences = NULL;
	GTask *task = NULL;

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

	saved_presences = g_list_store_new(PURPLE_TYPE_SAVED_PRESENCE);

	while(seagull_statement_step(backend->query_properties, &error)) {
		PurpleSavedPresence *saved_presence = NULL;
		const char *id = NULL;

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

			continue;
		}

		/* We have all the construct only properties, so let's create the
		 * instance.
		 */
		saved_presence = g_object_new(
			PURPLE_TYPE_SAVED_PRESENCE,
			"id", id,
			NULL);

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

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

			g_clear_object(&saved_presence);

			continue;
		}

		g_list_store_append(saved_presences, saved_presence);

		g_clear_object(&saved_presence);
	}

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

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

	g_clear_object(&task);
}

static GListModel *
purple_presence_manager_seagull_backend_load_saved_presences_finish(PurplePresenceManagerBackend *backend,
                                                                    GAsyncResult *result,
                                                                    GError **error)
{
	g_return_val_if_fail(PURPLE_IS_PRESENCE_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_presence_manager_seagull_backend_save_saved_presence_properties(PurplePresenceManagerSeagullBackend *backend,
                                                                       PurpleSavedPresence *saved_presence,
                                                                       GError **error)
{
	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 saved_presence. */
	success = seagull_statement_bind_object(backend->insert_properties,
	                                        NULL, G_OBJECT(saved_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_properties, error);
	if(error != NULL && *error != NULL) {
		return FALSE;
	}

	return TRUE;
}

static void
purple_presence_manager_seagull_backend_save_saved_presence_async(PurplePresenceManagerBackend *purple_backend,
                                                                  PurpleSavedPresence *saved_presence,
                                                                  GCancellable *cancellable,
                                                                  GAsyncReadyCallback callback,
                                                                  gpointer data)
{
	PurplePresenceManagerSeagullBackend *backend = NULL;
	GError *error = NULL;
	GTask *task = NULL;
	gboolean success = FALSE;

	backend = PURPLE_PRESENCE_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 _saved_presence properties. */
	success = purple_presence_manager_seagull_backend_save_saved_presence_properties(backend,
	                                                                                 saved_presence,
	                                                                                 &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_presence_manager_seagull_backend_save_saved_presence_finish(PurplePresenceManagerBackend *backend,
                                                                   GAsyncResult *result,
                                                                   GError **error)
{
	g_return_val_if_fail(PURPLE_IS_PRESENCE_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_presence_manager_seagull_backend_initable_init(GInitable *initable,
                                                      G_GNUC_UNUSED GCancellable *cancellable,
                                                      GError **error)
{
	PurplePresenceManagerSeagullBackend *backend = NULL;
	SeagullStatement *stmt = NULL;
	GError *local_error = NULL;
	gboolean result = FALSE;
	const char *migrations[] = {
		"01-initial.sql",
		"02-strict-tables.sql",
		"03-use-count.sql",
		NULL
	};

	backend = PURPLE_PRESENCE_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_prefixed_error(error, local_error, "delete-properties:");

		return FALSE;
	}
	backend->delete_properties = stmt;

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

		return FALSE;
	}
	backend->insert_properties = stmt;

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

		return FALSE;
	}
	backend->query_properties = stmt;

	return TRUE;
}

static void
purple_presence_manager_seagull_backend_initable_iface_init(GInitableIface *iface)
{
	iface->init = purple_presence_manager_seagull_backend_initable_init;
}

/******************************************************************************
 * GObject Implementation
 *****************************************************************************/
G_DEFINE_FINAL_TYPE_WITH_CODE(PurplePresenceManagerSeagullBackend,
                              purple_presence_manager_seagull_backend,
                              PURPLE_TYPE_PRESENCE_MANAGER_BACKEND,
                              G_IMPLEMENT_INTERFACE(G_TYPE_INITABLE,
                                                    purple_presence_manager_seagull_backend_initable_iface_init))

static void
purple_presence_manager_seagull_backend_finalize(GObject *obj) {
	PurplePresenceManagerSeagullBackend *backend = NULL;

	backend = PURPLE_PRESENCE_MANAGER_SEAGULL_BACKEND(obj);

	g_clear_pointer(&backend->filename, g_free);

	g_clear_object(&backend->delete_properties);
	g_clear_object(&backend->insert_properties);
	g_clear_object(&backend->query_properties);

	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_presence_manager_seagull_backend_parent_class)->finalize(obj);
}

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

	backend = PURPLE_PRESENCE_MANAGER_SEAGULL_BACKEND(obj);

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

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

	backend = PURPLE_PRESENCE_MANAGER_SEAGULL_BACKEND(obj);

	switch(param_id) {
	case PROP_FILENAME:
		purple_presence_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_presence_manager_seagull_backend_init(G_GNUC_UNUSED PurplePresenceManagerSeagullBackend *backend) {
}

static void
purple_presence_manager_seagull_backend_class_init(PurplePresenceManagerSeagullBackendClass *klass) {
	GObjectClass *obj_class = G_OBJECT_CLASS(klass);
	PurplePresenceManagerBackendClass *backend_class = NULL;

	obj_class->finalize = purple_presence_manager_seagull_backend_finalize;
	obj_class->get_property =
		purple_presence_manager_seagull_backend_get_property;
	obj_class->set_property =
		purple_presence_manager_seagull_backend_set_property;

	backend_class = PURPLE_PRESENCE_MANAGER_BACKEND_CLASS(klass);
	backend_class->delete_saved_presence_async =
		purple_presence_manager_seagull_backend_delete_saved_presence_async;
	backend_class->delete_saved_presence_finish =
		purple_presence_manager_seagull_backend_delete_saved_presence_finish;
	backend_class->load_saved_presences_async =
		purple_presence_manager_seagull_backend_load_saved_presences_async;
	backend_class->load_saved_presences_finish =
		purple_presence_manager_seagull_backend_load_saved_presences_finish;
	backend_class->save_saved_presence_async =
		purple_presence_manager_seagull_backend_save_saved_presence_async;
	backend_class->save_saved_presence_finish =
		purple_presence_manager_seagull_backend_save_saved_presence_finish;

	/**
	 * PurplePresenceManagerSeagullBackend: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
 *****************************************************************************/
PurplePresenceManagerBackend *
purple_presence_manager_seagull_backend_new(const char *filename,
                                            GError **error)
{
	return g_initable_new(
		PURPLE_TYPE_PRESENCE_MANAGER_SEAGULL_BACKEND,
		NULL,
		error,
		"filename", filename,
		NULL);
}

const char *
purple_presence_manager_seagull_backend_get_filename(PurplePresenceManagerSeagullBackend *backend) {
	g_return_val_if_fail(PURPLE_IS_PRESENCE_MANAGER_SEAGULL_BACKEND(backend),
	                     NULL);

	return backend->filename;
}
