/*
 * xrdesktop
 * Copyright 2018 Collabora Ltd.
 * Author: Lubosz Sarnecki <lubosz.sarnecki@collabora.com>
 * SPDX-License-Identifier: MIT
 */

#include <glib.h>
#include "xrd.h"


static GdkPixbuf *
_load_gdk_pixbuf (const gchar* name)
{
  GError * error = NULL;
  GdkPixbuf *pixbuf_rgb = gdk_pixbuf_new_from_resource (name, &error);

  if (error != NULL)
    {
      g_printerr ("Unable to read file: %s\n", error->message);
      g_error_free (error);
      return NULL;
    }

  GdkPixbuf *pixbuf = gdk_pixbuf_add_alpha (pixbuf_rgb, FALSE, 0, 0, 0);
  g_object_unref (pixbuf_rgb);
  return pixbuf;
}

static GulkanTexture *
_make_texture (GulkanClient *gc, const gchar *resource)
{
  GdkPixbuf *pixbuf = _load_gdk_pixbuf (resource);
  if (pixbuf == NULL)
    {
      g_printerr ("Could not load image.\n");
      return FALSE;
    }

  GulkanTexture *texture =
    gulkan_texture_new_from_pixbuf (gc, pixbuf,
                                    VK_FORMAT_R8G8B8A8_UNORM,
                                    VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
                                    TRUE);

  g_object_unref (pixbuf);

  return texture;
}

int
main ()
{
  XrdClient *client = xrd_client_new_with_mode (XRD_CLIENT_MODE_OVERLAY);

  GulkanClient *gc = xrd_client_get_gulkan (client);

  GulkanTexture *texture = _make_texture (gc, "/res/cat.jpg");

  VkExtent2D extent = gulkan_texture_get_extent (texture);

  float ppm = (float) extent.width / 0.25f;

  XrdWindow *window = xrd_window_new_from_pixels (client,
                                                  "win.",
                                                  extent.width,
                                                  extent.height,
                                                  ppm);

  xrd_client_add_window (client, window, TRUE, NULL);

  xrd_window_set_and_submit_texture (window, texture);

  GulkanDevice *device = gulkan_client_get_device (gc);
  gulkan_device_wait_idle (device);

  xrd_window_submit_texture (window);

  g_print ("bye bye\n");

  // TODO: Ref window in client
  //g_object_unref (window);

  g_object_unref (client);
  return 0;
}
