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

#include "db-result.h"

/**
 * SECTION: db-result
 * @Short_description: 
 * @Title: DbResult
 * @See_also: #DbResultSet
 **/
G_DEFINE_BOXED_TYPE (DbResult, db_result, db_result_copy, db_result_free);

DbResult * db_result_new ()
{
	DbResult * obj = g_new (DbResult, 1);
	return obj;
}

DbRow * db_result_get_row (const DbResult * obj, gint row_index)
{
	g_return_val_if_fail (obj, NULL);
	g_return_val_if_fail (row_index >= 0 && row_index < obj->nrows, NULL);

	return g_ptr_array_index (obj->data, row_index);
}	

void db_result_remove_row (DbResult * obj, gint row_index)
{
	g_return_if_fail (obj);
	g_return_if_fail (row_index >= 0 && row_index < obj->nrows);
}

/**
 * db_result_copy:
 * @obj: a #DbResult
 *
 * Makes a copy of a #DbResult.
 *
 * Return value: a newly allocated #DbResult, with the same contents
 **/
DbResult * db_result_copy (const DbResult * obj)
{
	gint n;
	DbResult * result;

	g_return_val_if_fail (obj, NULL);

	result = g_new (DbResult, 1);
	result->nrows = obj->nrows;
	result->ncols = obj->ncols;
	result->column = g_new (DbColumn, obj->ncols);
	result->data = g_ptr_array_new_full (obj->nrows + 15,
		(GDestroyNotify) db_row_free);
		
	for (n = 0; n < obj->ncols; n++)
	{
		result->column[n].info = obj->column[n].info;
		result->column[n].spec = gvn_param_spec_copy (obj->column[n].spec);
		result->column[n].table = g_strdup (obj->column[n].table);
		result->column[n].table_alias = g_strdup (obj->column[n].table_alias);
		result->column[n].schema = g_strdup (obj->column[n].schema);
		result->column[n].name = g_strdup (obj->column[n].name);
		result->column[n].alias = g_strdup (obj->column[n].alias);
	}
		
	for (n = 0; n < obj->nrows; n++)
		g_ptr_array_add (result->data,
			db_row_copy (g_ptr_array_index (obj->data, n)));
	
	return result;
}

/**
 * db_result_free:
 * @obj: a #DbResult
 *
 * Frees a #DbResult.
 **/
void db_result_free (DbResult * obj)
{
	g_return_if_fail (obj);

	if (obj->data)
		g_ptr_array_unref (obj->data);

	if (obj->column)
	{
		int i;

		for (i = 0; i < obj->ncols; i++)
		{
			DbColumn col = obj->column[i];
			gvn_param_spec_free (col.spec);
			g_free (col.name);
			g_free (col.alias);
			g_free (col.table);
			g_free (col.table_alias);
			g_free (col.schema);
		}

		g_free (obj->column);
	}

	g_free (obj);
}