// gcc -g -Wall -o testcase testcase.c `pkg-config --libs --cflags rest-0.7 goa-1.0 json-glib-1.0`

#include <json-glib/json-glib.h>

static void
parse_item (JsonReader *reader)
{
	const char *id, *url;

	id = g_strdup (json_reader_get_member_name (reader));
	if (!id) {
		g_message ("couldn't read member id");
		return;
	}
	g_message ("id: %s", id);

	if (!json_reader_read_member (reader, "resolved_url")) {
		const GError *error;
		/* No resolved URL for item */
		error = json_reader_get_error (reader);
		g_message ("Error getting resolved_url: %s", error->message);
		json_reader_end_member (reader);
		if (!json_reader_read_member (reader, "given_url")) {
			error = json_reader_get_error (reader);
			g_message ("Error getting given_url: %s", error->message);
			g_assert_not_reached ();
			return;
		}
	}
	url = g_strdup (json_reader_get_string_value (reader));
	json_reader_end_member (reader);

	g_message ("url: %s", url);
}

static void
parse_json (JsonParser *parser)
{
	JsonReader *reader;
	int num;

	reader = json_reader_new (json_parser_get_root (parser));

	num = json_reader_count_members (reader);
	g_assert (num > 0);

	/* Grab the list */
	if (json_reader_read_member (reader, "list")) {
		char **members;
		guint i;

		members = json_reader_list_members (reader);
		if (members != NULL) {
			for (i = 0; members[i] != NULL; i++) {
				if (!json_reader_read_member (reader, members[i])) {
					g_message ("failed to find id %s", members[i]);
					json_reader_end_member (reader);
					continue;
				}
				parse_item (reader);
				json_reader_end_member (reader);
			}
		}
		g_strfreev (members);
	}
	json_reader_end_member (reader);
	g_clear_object (&reader);
}

int main (int argc, char **argv)
{
	JsonParser *parser;
	GError *error = NULL;

	parser = json_parser_new ();
	if (json_parser_load_from_file (parser,
					"testcase.json",
					&error) == FALSE) {
		g_message ("couldn't parse json file: %s", error->message);
		g_error_free (error);
		return 1;
	}

	parse_json (parser);

	return 0;
}
