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

/**
 * SECTION: db-row
 * @Short_description: a row from a #DbModel
 * @Title: DbRow
 * @See_also: #DbModel
 * 
 * #DbRow represents a row in a #DbModel. 
 **/
G_DEFINE_BOXED_TYPE (DbRow, db_row, db_row_copy, db_row_free);

/**
 * db_row_new:
 * @len: the lenght of the #DbRow.
 * @position: the position where the returned #DbRow will be placed.
 * 
 * Sets a newly allocated #DbRow of lenght @len with position @postition.
 * This new structure must be freed using db_row_free().
 * 
 * Return value: a new #DbRow
 **/
DbRow *	db_row_new (gint len, gint position)
{
	DbRow * row = g_slice_new (DbRow);
	row->value = g_new0 (GValue, len);
	row->position = position;
	row->len = len;
	return row;
}

/**
 * db_row_free:
 * @row: the row that you want to free.
 * 
 * Frees a #DbRow of a #DbResult.
 **/
void db_row_free (DbRow * row)
{
	gint n;

	for (n = 0; n < row->len; n++)
		g_value_unset (&row->value[n]);

	g_free (row->value);
	g_slice_free (DbRow, row);
}

/**
 * db_row_copy:
 * @row: a #DbRow
 * 
 * Copies a #DbRow.
 * 
 * Return value: a new copy of @row
 **/
DbRow * db_row_copy (const DbRow * row)
{
	gint n;
	DbRow * new;

	g_return_val_if_fail (row, NULL);

	new = g_new (DbRow, 1);
	new->len = row->len;
	new->position = row->position;
	new->value = g_new (GValue, new->len);

	for (n = 0; n < new->len; n++)
		g_value_copy
			(g_value_init (&new->value[n], G_VALUE_TYPE (&row->value))
			,&row->value[n]);

	return new;
}

/**
 * db_row_get_value:
 * @row: a #DbRow
 * @index: the index of the value in @row
 * 
 * Returns the value placed in the position @index of @row.
 *
 * Return value: a #GValue 
 **/
const GValue * db_row_get_value (const DbRow * row, gint index)
{
	g_return_val_if_fail (row, NULL);
	g_return_val_if_fail (index >= 0 && index < row->len, NULL);

	return &row->value[index];
}

/**
 * db_row_get_position:
 * @row: a #DbRow
 * 
 * Returns the position where @row in the model it belongs to.
 *
 * Return value: the position of @row in its model or -1 if index is out of
 **/
gint db_row_get_position (const DbRow * row)
{
	g_return_val_if_fail (row, -1);

	return row->position;
}