#include <glib.h>
#include <gdk-pixbuf/gdk-pixbuf.h>

#include "valid.1.xpm"

typedef struct
{
  int dummy;
} Fixture;

static void
setup (Fixture *f,
       gconstpointer context G_GNUC_UNUSED)
{
}

static void
test_format (Fixture *f,
             gconstpointer context)
{
  g_autoptr(GdkPixbufLoader) loader = NULL;
  g_autoptr(GError) error = NULL;
  g_autofree char *contents = NULL;
  GdkPixbuf *pixbuf = NULL;
  size_t len = 0;
  const char *filename = context;
  const char *ext;
  const char *type;
  gboolean ok;

  ext = strrchr (filename, '.');
  g_assert_nonnull (ext);
  g_assert_cmpint (*ext, ==, '.');
  ext++;

  /* Mostly the image format name is the same as the extension, but there
   * are some exceptions */
  if (g_str_equal (ext, "xpm"))
    type = "legacy-xpm";
  else if (g_str_equal (ext, "ppm"))
    type = "pnm";
  else
    type = ext;

  loader = gdk_pixbuf_loader_new_with_type (type, &error);
  g_assert_no_error (error);
  g_assert_nonnull (loader);

  ok = g_file_get_contents (filename, &contents, &len, &error);
  g_assert_no_error (error);
  g_assert_true (ok);

  ok = gdk_pixbuf_loader_write (loader, (const guchar *) contents, len, &error);
  g_assert_no_error (error);
  g_assert_true (ok);

  ok = gdk_pixbuf_loader_close (loader, &error);
  g_assert_no_error (error);
  g_assert_true (ok);

  pixbuf = gdk_pixbuf_loader_get_pixbuf (loader);
  g_assert_nonnull (pixbuf);
}

static void
test_legacy_xpm (Fixture *f,
                 gconstpointer context G_GNUC_UNUSED)
{
  g_autoptr(GdkPixbuf) pb = NULL;
  const char **xpm_lines = (const char **) apple_red_xpm;

  G_GNUC_BEGIN_IGNORE_DEPRECATIONS
  pb = gdk_pixbuf_new_from_xpm_data (xpm_lines);
  G_GNUC_END_IGNORE_DEPRECATIONS

  g_assert_nonnull (pb);
  g_assert_cmpint (gdk_pixbuf_get_height (pb), ==, 48);
  g_assert_cmpint (gdk_pixbuf_get_width (pb), ==, 48);
}

static void
teardown (Fixture *f,
          gconstpointer context G_GNUC_UNUSED)
{
}

int
main (int argc,
      char **argv)
{
  g_test_init (&argc, &argv, NULL);

  g_test_add ("/bmp", Fixture, "valid.1.bmp", setup, test_format, teardown);
  g_test_add ("/gif", Fixture, "valid.1.gif", setup, test_format, teardown);
  g_test_add ("/jpeg", Fixture, "valid.1.jpeg", setup, test_format, teardown);
  g_test_add ("/png", Fixture, "valid.1.png", setup, test_format, teardown);
#if 0
  /* Legacy format, and not supported by glycin right now? */
  g_test_add ("/ppm", Fixture, "valid.1.ppm", setup, test_format, teardown);
#endif
  g_test_add ("/tga", Fixture, "valid.1.tga", setup, test_format, teardown);
  g_test_add ("/tiff", Fixture, "valid.1.tiff", setup, test_format, teardown);
  g_test_add ("/xbm", Fixture, "valid.1.xbm", setup, test_format, teardown);
  g_test_add ("/xpm", Fixture, "valid.1.xpm", setup, test_format, teardown);

  g_test_add ("/legacy-xpm", Fixture, NULL, setup, test_legacy_xpm, teardown);

  return g_test_run ();
}
