/*
 * Copyright (C) 2025 The Phosh Developers
 *
 * SPDX-License-Identifier: LGPL-2.1+
 */

#include "lcb-dbus.h"
#include "lcb-main.h"
#include "lcb-names.h"

static LcbDBusCbd   *_proxy = NULL;
static GCancellable *_cancellable = NULL;


/**
 * lcb_init:
 * @error: Error information
 *
 * Initialize libcellbroadcast.
 * This must be called before any other of libcellbroadcast's functions.
 *
 * Returns: %TRUE if successful, or %FALSE on error.
 */
gboolean
lcb_init (GError **error)
{
  static gsize init = FALSE;

  if (g_once_init_enter (&init)) {
    _cancellable = g_cancellable_new ();
    _proxy = lcb_dbus_cbd_proxy_new_for_bus_sync (G_BUS_TYPE_SESSION,
                                                  G_DBUS_PROXY_FLAGS_NONE,
                                                  CB_DBUS_NAME,
                                                  CB_DBUS_PATH,
                                                  _cancellable,
                                                  error);
    g_once_init_leave (&init, TRUE);
  }

  return !!_proxy;
}


/**
 * lcb_uninit:
 *
 * Uninitialize the library when no longer used. Usually called
 * on program shutdown.
 */
void
lcb_uninit (void)
{
  g_cancellable_cancel (_cancellable);
  g_clear_object (&_cancellable);
  g_clear_object (&_proxy);
}

/**
 * lcb_is_innited:
 *
 * Whether libcellbroadcast is initialized.
 *
 * Returns: %TRUE, if library is initialized, %FALSE otherwise.
 */
gboolean
lcb_is_initted (void)
{
  return !!_proxy;
}

/**
 * lcb_get_proxy:
 *
 * This can be used to access the lower level API e.g. to listen to
 * property changes. The object is not owned by the caller. Don't
 * unref it after use.
 *
 * Returns: (transfer none): The DBus proxy.
 */
LcbDBusCbd *
lcb_get_proxy (void)
{
  g_return_val_if_fail (LCB_DBUS_IS_CBD (_proxy), NULL);

  return _proxy;
}
