/*
 * Copyright (C) 2025 The Phosh.mobi e.V.
 *
 * SPDX-License-Identifier: GPL-3.0+
 *
 * Author: Evangelos Ribeiro Tzaras <devrtz@fortysixandtwo.eu>
 */

#define LIBCELLBROADCAST_USE_UNSTABLE_API
#include "libcellbroadcast.h"

#include <locale.h>
#include <glib.h>

int
main (int argc, char *argv[0])
{
  g_autoptr (GListModel) messages = NULL;
  g_autoptr (GOptionContext) opt_context = NULL;
  g_autoptr (GError) err = NULL;
  gboolean success = TRUE;
  gboolean do_list = FALSE;
  const GOptionEntry options [] = {
    {"list-messages", 'm', 0, G_OPTION_ARG_NONE, &do_list,
     "Lists all stored cell broadcast messages", NULL},
    { NULL, 0, 0, G_OPTION_ARG_NONE, NULL, NULL, NULL }
  };

  setlocale (LC_ALL, "");
  opt_context = g_option_context_new ("- A cli for cellbroadcastd");
  g_option_context_add_main_entries (opt_context, options, NULL);
  if (!g_option_context_parse (opt_context, &argc, &argv, &err)) {
    g_warning ("%s", err->message);
    return 1;
  }

  if (!lcb_init (&err)) {
    g_print ("Failed to init libcellbroadcast: %s\n", err->message);
    return 1;
  }

  if (!do_list)
    do_list = TRUE; /* we currently don't have any other options */

  if (do_list) {
    guint n_messages;

    messages = lcb_cbd_get_messages_sync (&err);
    success = !!messages;
    if (!messages) {
      g_printerr ("Failed to retrieve cell broadcast messages: %s\n", err->message);
      goto exit;
    }

    n_messages = g_list_model_get_n_items (messages);
    for (guint i = 0; i < n_messages; i++) {
      g_autoptr (LcbMessage) msg = g_list_model_get_item (messages, i);
      g_autofree char *severity = NULL;

      severity = g_flags_to_string (LCB_TYPE_SEVERITY_LEVEL,
                                    lcb_message_get_severity (msg));

      g_print ("Channel      : %" G_GUINT16_FORMAT "\n"
               "Message code : %" G_GUINT16_FORMAT "\n"
               "Update       : %" G_GUINT16_FORMAT "\n"
               "Timestamp    : %" G_GUINT64_FORMAT "\n"
               "Severity     : %s\n"
               "Text         : %s\n",
               lcb_message_get_channel (msg),
               lcb_message_get_msg_code (msg),
               lcb_message_get_update (msg),
               lcb_message_get_timestamp (msg),
               severity,
               lcb_message_get_text (msg));

      if (i < n_messages - 1)
        g_print ("\n");
    }

    if (g_list_model_get_n_items (messages) == 0)
      g_print ("No cell broadcast messages have yet been received\n");
  }

 exit:

  lcb_uninit ();
  return !success;
}
