#include <string.h>
#include <stdlib.h>
#include <gio/gio.h>
#include <librsvg/rsvg.h>
#include <gdk-pixbuf/gdk-pixbuf.h>

#define RESOURCE_SCHEME "x-rsvg-resource:"

static char *global_text;

static const char svg_data[] =
  "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n"
  "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"200px\" height=\"200px\">\n"
    "<g>\n"
      "<rect x=\"0\" y=\"0\" width=\"200\" height=\"200\" fill=\"red\"/>\n"
      "<text x=\"10\" y=\"180\" style=\"font-size: 50\">\n"
        "<xi:include href=\"x-rsvg-resource:text\" parse=\"text\"/>\n"
      "</text>\n"
    "</g>\n"
  "</svg>\n";

typedef struct _MyRsvgHandle MyRsvgHandle;
typedef struct _MyRsvgHandleClass MyRsvgHandleClass;

struct _MyRsvgHandle {
  RsvgHandle parent_instance;
};

struct _MyRsvgHandleClass {
  RsvgHandleClass parent_class;
};

static GType my_rsvg_handle_get_type (void);
G_DEFINE_TYPE (MyRsvgHandle, my_rsvg_handle, RSVG_TYPE_HANDLE);

static GInputStream *
my_rsvg_handle_acquire_resource (RsvgHandle *handle,
                                 const char *href,
                                 const char *base_uri,
                                 GError **error)
{
  const char *res;
  g_print ("my-acquire-resource href %s\n", href);

  if (!href || !g_str_has_prefix (href, RESOURCE_SCHEME))
    return RSVG_HANDLE_CLASS (my_rsvg_handle_parent_class)->acquire_resource (handle, href, base_uri, error);

  res = href + strlen (RESOURCE_SCHEME);
  if (strcmp (res, "text") == 0) {
    return g_memory_input_stream_new_from_data (global_text, strlen (global_text), NULL);
  }

  return NULL;
}

static void my_rsvg_handle_init (MyRsvgHandle *handle)
{
}

static void my_rsvg_handle_class_init (MyRsvgHandleClass *klass)
{
  RsvgHandleClass *handle_class = RSVG_HANDLE_CLASS (klass);

  handle_class->acquire_resource = my_rsvg_handle_acquire_resource;
}

int
main (int argc, char **argv)
{
  RsvgHandle *handle;
  GdkPixbuf *pixbuf;
  gboolean ret;
  GError *err = NULL;

  g_type_init ();
  rsvg_init ();

  if (argc != 3) {
    g_printerr ("Usage: %s OUTFILE TEXT\n", argv[0]);
    exit (1);
  }

  global_text = argv[2];

  handle = g_object_new (my_rsvg_handle_get_type (), NULL);
  rsvg_handle_set_base_uri (handle, "x-rsvg-resource:test.svg");
  ret = rsvg_handle_write (handle, svg_data, strlen (svg_data), &err);
  g_assert_no_error (err);
  g_assert (ret);
  ret = rsvg_handle_close (handle, &err);
  g_assert_no_error (err);
  g_assert (ret);

  pixbuf = rsvg_handle_get_pixbuf (handle);
  g_assert (pixbuf != NULL);
  gdk_pixbuf_save (pixbuf, argv[1], "png", &err, NULL);
  g_assert_no_error (err);
  g_object_unref (pixbuf);

  g_object_unref (handle);

  return 0;
}
