/*
 * Copyright (C) 2013 - 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 "sql-param-object.h"
#include "sql-holder.h"

/**
 * sql_param_object:
 * Return value: (transfer full):
 **/
GParamSpec *
sql_param_object (const gchar * name, const gchar * nick,
	const gchar * blurb, GType object_type, GParamFlags flags)
{
	GParamSpec * pspec;

	g_return_val_if_fail (g_type_is_a (object_type, SQL_TYPE_OBJECT), NULL);

	pspec = g_param_spec_internal (SQL_TYPE_PARAM_OBJECT
		,name
		,nick
		,blurb
		,flags
	);
	return pspec;
}

static void
sql_param_object_init (GParamSpec * pspec) {}

static void
sql_param_object_set_default (GParamSpec * pspec, GValue * value)
{
	g_value_set_object (value, NULL);
}

static gboolean
sql_param_object_validate (GParamSpec * pspec, GValue * value)
{
	GType type;
	gboolean change;
	GObject * object = g_value_get_object (value);
	
	if (!object)
		return FALSE;
		
	type = G_OBJECT_TYPE (object);
	
	change = !(
		g_value_type_compatible (type, G_PARAM_SPEC_VALUE_TYPE (pspec))
		|| g_value_type_compatible (type, SQL_TYPE_HOLDER)
	);

	if (change)
		g_value_set_object (value, NULL);

	return change;
}

static gint
sql_param_object_values_cmp (GParamSpec * pspec, const GValue * a, const GValue * b)
{
  guint8 * pa = g_value_get_object (a);
  guint8 * pb = g_value_get_object (b);

  return pa < pb ? -1 : pa > pb;
}

GType
sql_param_object_get_type ()
{
	static GType type = 0;
	
	if (!type)
	{
		GParamSpecTypeInfo pspec_info =
		{
			sizeof (SqlParamObject)
			,16
			,sql_param_object_init
			,SQL_TYPE_OBJECT
			,NULL
			,sql_param_object_set_default
			,sql_param_object_validate
			,sql_param_object_values_cmp
		};

		type = g_param_type_register_static (
			g_intern_static_string ("SqlParamObject"), &pspec_info);
	}
	
	return type;
}