/*
 * Copyright (C) 2012 - Juan Ferrer Toribio
 *
 * This program 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 3 of the License, or
 * (at your option) any later version.
 *
 * This program 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 program. If not, see <http://www.gnu.org/licenses/>.
 */

#ifndef DB_REQUEST_H
#define DB_REQUEST_H

#include <sql/sql.h>
#include "db-result-set.h"

#define DB_REQUEST_LOG_DOMAIN		(g_quark_from_string ("DbRequest"))

#define DB_TYPE_REQUEST				(db_request_get_type ())
#define DB_REQUEST(obj)				(G_TYPE_CHECK_INSTANCE_CAST ((obj), DB_TYPE_REQUEST, DbRequest))
#define DB_IS_REQUEST(obj)			(G_TYPE_CHECK_INSTANCE_TYPE ((obj), DB_TYPE_REQUEST))
#define DB_REQUEST_CLASS(klass)		(G_TYPE_CHECK_CLASS_CAST ((klass), DB_TYPE_REQUEST, DbRequestClass))
#define DB_IS_REQUEST_CLASS(klass)	(G_TYPE_CHECK_CLASS_TYPE ((klass), DB_TYPE_REQUEST))
#define DB_REQUEST_GET_CLASS(obj)	(G_TYPE_INSTANCE_GET_CLASS ((obj), DB_TYPE_REQUEST, DbRequestClass))

typedef struct _DbRequest DbRequest;
typedef struct _DbRequestClass DbRequestClass;

typedef void (*DbRequestDoneCallback)	(DbRequest * obj, gpointer user_data);

#include "db-conn.h"

typedef enum
{
	 DB_REQUEST_CLEAN
	,DB_REQUEST_LOADING
	,DB_REQUEST_DONE
	,DB_REQUEST_CANCELED
	,DB_REQUEST_ERROR
}
DbRequestStatus;

typedef enum
{
	 DB_REQUEST_ERROR_CANCELED
	,DB_REQUEST_ERROR_NO_EXECUTED
}
DbRequestError;

struct _DbRequest
{
	GObject parent;

	/* <private> */
	DbConn * conn;
	gchar * sql;
	DbResultSet * result_set;
	GError * error;
	DbRequestStatus status;
	GMutex mutex;
	DbRequestDoneCallback callback;
	gpointer user_data;
	GDestroyNotify notify;
};

struct _DbRequestClass
{
	/* <private> */
	GObjectClass parent;
};

GType				db_request_get_type			();
DbRequest *			db_request_new				(DbConn * conn, const gchar * sql);
DbRequest *			db_request_new_with_stmt	(DbConn * conn, SqlStmt * stmt);
DbResult *			db_request_fetch_result		(DbRequest * obj, GError ** err);
gint				db_request_fetch_non_select	(DbRequest * obj, GError ** err);
gboolean			db_request_fetch_value		(DbRequest * obj, GValue * value, GError ** err);
gboolean			db_request_exec				(DbRequest * obj, GError ** err);
void				db_request_set_callback		(DbRequest * obj, DbRequestDoneCallback callback, gpointer user_data, GDestroyNotify notify);
void				db_request_complete			(DbRequest * obj);
void				db_request_cancel			(DbRequest * obj);
gchar *				db_request_get_sql			(DbRequest * obj);

#endif