/*
 * Copyright (C) 2019 Purism SPC
 * SPDX-License-Identifier: GPL-3.0+
 * Author: Guido Günther <agx@sigxcpu.org>
 */
#include "libgtherm.h"

#include <glib.h>
#include <gio/gio.h>

#include <locale.h>


static GthManager *
gthcli_get_manager_sync (GDBusConnection *connection)
{
  GthManager *manager;
  gchar *name_owner;
  GError *error = NULL;

  manager = gth_manager_new_sync (connection,
				  G_DBUS_OBJECT_MANAGER_CLIENT_FLAGS_DO_NOT_AUTO_START,
				  NULL,
				  &error);
  if (!manager) {
    g_printerr ("error: couldn't create manager: %s\n",
		error ? error->message : "unknown error");
    exit (EXIT_FAILURE);
  }

  name_owner = g_dbus_object_manager_client_get_name_owner (G_DBUS_OBJECT_MANAGER_CLIENT (manager));
  if (!name_owner) {
    g_printerr ("error: couldn't find the gthd process in the bus\n");
    exit (EXIT_FAILURE);
  }

  g_debug ("Gthd found at '%s'", name_owner);
  g_free (name_owner);

  return manager;
}


static void
print_tzone (GthThermalZone *tzone)
{
  const char * const *cdevs;

  cdevs = gth_thermal_zone_get_cooling_devices_dbus_paths (tzone);

  g_print ("      dbus path: %s\n", gth_thermal_zone_get_path (tzone));
  g_print ("           type: %s\n", gth_thermal_zone_get_type_ (tzone));
  g_print ("    temperature: %.2f°C\n", gth_thermal_zone_get_temperature (tzone) / 1000.0);
  if (cdevs && cdevs[0])
    g_print ("cooling devices: %s\n", cdevs[0]);
  for (int i = 1; cdevs[i]; i++)
    g_print ("                 %s\n", cdevs[i]);
  g_print ("\n");
}


static void
print_cdev (GthCoolingDevice *cdev)
{
  g_print ("    dbus path: %s\n", gth_cooling_device_get_path (cdev));
  g_print ("         type: %s\n", gth_cooling_device_get_type_ (cdev));
  g_print ("    max state: %d\n", gth_cooling_device_get_max_state (cdev));
  g_print ("current state: %d\n", gth_cooling_device_get_current_state (cdev));
  g_print ("\n");
}


int main(void)
{
  g_autoptr(GError) err = NULL;
  g_autoptr(GDBusConnection) connection = NULL;
  g_autoptr(GthManager) manager = NULL;
  GPtrArray *cdevs, *tzones;

  setlocale (LC_ALL, "");

  connection = g_bus_get_sync (GTH_DBUS_TYPE, NULL, &err);
  if (!connection) {
    g_printerr ("error: couldn't get bus: %s\n",
		err ? err->message : "unknown error");
    exit (EXIT_FAILURE);
  }

  manager = gthcli_get_manager_sync (connection);

  g_print ("\n");
  tzones = gth_manager_get_thermal_zones (manager);
  g_debug ("Found %d thermal zones\n", tzones->len);
  g_print ("Thermal Zones\n");
  g_print ("-------------\n");
  for (int i = 0; i < tzones->len; i++) {
    print_tzone(g_ptr_array_index (tzones, i));
  }

  cdevs = gth_manager_get_cooling_devices (manager);
  g_debug ("Found %d cooling devices\n", cdevs->len);
  g_print ("Cooling Devices\n");
  g_print ("---------------\n");
  for (int i = 0; i < cdevs->len; i++) {
    print_cdev(g_ptr_array_index (cdevs, i));
  }

  return EXIT_SUCCESS;
}
