/* Invoke a function from a given swf and print the result.
 * 2009-02-22 hyc@highlandsun.com
 *
 * Tested with swfdec-0.9.2. Uses library-internal APIs, use
 * at your own risk...
 *
 * Compiled/linked on Ubuntu 8.10 as:
 * gcc -g decswf.c -I/usr/include/swfdec -I/usr/include/glib-2.0 -I/usr/lib/glib-2.0/include -I/usr/include/cairo -o decswf -lswfdec-0.9
 *
 * Invoke as:
 *   decswf file://<absolute path to swf> <key>
 *
 */
#include <stdio.h>
#include <swfdec/swfdec.h>

/* These are defined internally in the library... */
struct _SwfdecSandbox;

struct _SwfdecSandbox *swfdec_sandbox_get_for_url(SwfdecPlayer *,
	SwfdecURL *,guint,gboolean);

int main (int argc, char **argv)
{
	SwfdecPlayer* player;
	SwfdecAsContext *ctx;
	SwfdecAsValue in, out;
	SwfdecAsObject *obj;
	struct _SwfdecSandbox *sbox;
	const char *txt;
	gboolean res;

	if (argc < 2) 
	{
		fprintf(stderr, "usage: %s URL PID", argv[0]);
		return 1;
	}
	
	/* Create a new player */
	player = swfdec_player_new (NULL);

	/* Set the URL or filepath */
	SwfdecURL* url = swfdec_url_new(argv[1]);
	if (!url)
	{
		fprintf(stderr, "Invalid URL %s\n", argv[1]);
		return 1;
	}
	swfdec_player_set_url(player,url);

	// We wait till the initialization is completed
	while (!swfdec_player_is_initialized (player))
	{
			long next = swfdec_player_get_next_event (player);
			if (next < 0)
			{
					/* not a flash file */
					return 0;
			}
			swfdec_player_advance (player, next);
	}

	/* Just for convenience */
	ctx = SWFDEC_AS_CONTEXT(player);

	/* Every string we use must be a garbage-collected string */
	txt = swfdec_as_context_get_string(ctx, argv[2]);
	SWFDEC_AS_VALUE_SET_STRING(&in, txt);

	/* Get the sandbox and activate it
	 * Use Flash version 8, no network access
	 */
	sbox = swfdec_sandbox_get_for_url(player, url, 8, 0);
	swfdec_sandbox_use(sbox);

	obj = ctx->global;
	txt = swfdec_as_context_get_string(ctx, "S");	
	res = swfdec_as_object_get_variable(obj, txt, &out);
	if (!res) {
		fprintf(stderr, "class S not found\n");
		return 1;
	}
	obj = SWFDEC_AS_VALUE_GET_OBJECT(out);

	txt = swfdec_as_context_get_string(ctx, "dec");	
	res = swfdec_as_object_call(obj,txt,1,&in,&out);
	txt = swfdec_as_value_to_string(ctx,out);
	puts(txt);
	return !res;
}
