#include <adwaita.h>
#include <libsoup/soup.h>
#include "gis-ubuntupro-page.h"

gboolean
parse_ua_status(gchar **contents, gsize *len)
{
    g_autoptr(GError) error = NULL;

    if (!g_file_get_contents("/var/lib/ubuntu-advantage/status.json",
                             contents, len, &error)) {
        g_warning("Unable to read pro status: %s\n", error->message);
        return FALSE;
    }
    return TRUE;
}

gboolean
get_ubuntu_advantage_attached(gboolean *attached)
{
  g_autoptr(GError) error = NULL;
  g_autoptr(GDBusConnection) bus = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, &error);
  if (bus == NULL) {
    g_warning ("Failed to get system bus: %s", error->message);
    return FALSE;
  }

  g_autoptr(GVariant) result = g_dbus_connection_call_sync (bus,
      "com.canonical.UbuntuAdvantage",
      "/com/canonical/UbuntuAdvantage/Manager",
      "org.freedesktop.DBus.Properties",
      "Get",
      g_variant_new ("(ss)", "com.canonical.UbuntuAdvantage.Manager", "Attached"),
      G_VARIANT_TYPE ("(v)"),
      G_DBUS_CALL_FLAGS_NONE,
      -1,
      NULL,
      &error);
  if (result == NULL) {
    g_warning ("Failed to contact Ubuntu Advantage D-Bus service: %s", error->message);
    return FALSE;
  }

  g_autoptr(GVariant) value = NULL;
  g_variant_get (result, "(v)", &value);
  if (!g_variant_is_of_type (value, G_VARIANT_TYPE("b"))) {
    g_warning ("Attached property has wrong type");
    return FALSE;
  }
  g_variant_get (value, "b", attached);

  return TRUE;
}

char *
get_item (const char *buffer, const char *name)
{
  g_autofree gchar *label = NULL;
  gchar *start = NULL, *end = NULL;
  gchar end_char;

  label = g_strconcat (name, "=", NULL);
  if ((start = strstr (buffer, label)) != NULL) {
    start += strlen (label);
    end_char = '\n';
    if (*start == '"') {
      start++;
      end_char = '"';
    }
    end = strchr (start, end_char);
  }

  if (start != NULL && end != NULL)
    return g_strndup (start, end - start);
  else
    return NULL;
}

gboolean
is_lts ()
{
  g_autofree gchar *buffer = NULL;
  g_autofree gchar *version = NULL;

  if (g_file_get_contents ("/etc/os-release", &buffer, NULL, NULL))
    version = get_item (buffer, "VERSION");

  return version && g_strrstr (version, "LTS") != NULL;
}

gboolean
is_ubuntupro_supported ()
{
  return is_lts ();
}

/* Routine from Gnome Control Center
 * https://gitlab.gnome.org/GNOME/gnome-control-center/-/commit/a3b8964a */
gboolean
is_dark_theme (GtkWidget *widget)
{
  g_autofree char *theme_name = NULL;

  theme_name = g_strdup (g_getenv ("GTK_THEME"));
  if (theme_name != NULL) {
    return g_str_has_suffix (theme_name, "-dark");
  }

  AdwStyleManager *manager = adw_style_manager_get_default ();
  return adw_style_manager_get_dark (manager);
}

void
itemize(gchar *str, const gchar *append, gsize len)
{
  g_strlcat(str, "• ", len);
  g_strlcat(str, append, len);
  g_strlcat(str, "\n", len);
}
