/*
 * showcommands.c
 * (C) Christian Magnusson 2000, Email: d1mag@dtek.chalmers.se
 * This program is copyright, and covered by the Gnu Public License.
 * The Q bot.
 */

#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#include "settings.h"
#include "bottypes.h"
#include "globals.h"
#include "dl.h"

void m_showcommands(char *a);

MODULE_PUBLIC int _init_showcommands(void *a, void *b)
{
  dl_command_entry_t *dl = a;
  if(!a) return 0;

  snprintf(dl->help, MAX_COMMAND_HELP_LEN,
	   "/msg %s SHOWCOMMANDS\nLists the commands available on the bot and the level of access required for each. This won't list commands above your level.\n"
	   , BOT_NAME);
  snprintf(dl->summary, MAX_COMMAND_SUMMARY_LEN,
	   "Lists all the commands on the bot.");
  dl->level = 0;
#if 0
  dl->func = m_showcommands;
#else
  dl->func = (void (*)(char*)) DL_sym(dl->val, "m_showcommands");
#endif
  return 1;
}

MODULE_PUBLIC int _remove_showcommands(char *a, char *b)
{
  remove_command("showcommands");
  return 1;
}

MODULE_PUBLIC void m_showcommands(char *a)
{
  dl_command_entry_t *cmd;
  ListElem *el;
  char *ptr;
  int j;
  int cur_level = 0;
  int max_level, next_level;
  char buffer[512];
  int level;
  if(!sender_au) return;
  level = sender_au->auth;

  if(sender_au->dbuser) {
    log("From: %s showcommands\n", sender_au->dbuser->nick);
  }

  max_level = 0;
 retry_it:
  next_level = 2000;
  el = GetFirstH(commands);
  while(el) {
    cmd = (dl_command_entry_t *)el->data;

    if(cmd->level > max_level) max_level = cmd->level;

    if(cmd->level > cur_level && cmd->level < next_level) {
      next_level = cmd->level;
    }

    if(cmd->level == cur_level && cmd->level <= level) {
      memset(buffer, 0, 512);
      strncpy(buffer, cmd->name, 256);
      /* truncate line feeds and CR since they cause core dump on 2.10.07 */
      ptr = strstr(buffer, "\n"); if(ptr) *ptr = '\0';
      ptr = strstr(buffer, "\r"); if(ptr) *ptr = '\0';
      strcat(buffer, " ");
      strncat(buffer, cmd->summary, 256);
      /* truncate line feeds and CR since they cause core dump on 2.10.07 */
      ptr = strstr(buffer, "\n"); if(ptr) *ptr = '\0';
      ptr = strstr(buffer, "\r"); if(ptr) *ptr = '\0';
      j = strlen(buffer);
      sprintf(&buffer[j], " - level %d.", cmd->level);
      /* Should perhaps dump_message(), but since I want all text on one
	 single row, I chose this method.
      */
      say_sender(buffer);
    }
    el = GetSuccH(commands, el);
  }
  if(cur_level == max_level) return;

  if(next_level > cur_level) {
    cur_level = next_level;
    goto retry_it;
  }
  return;
}
