/*
 * glist.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_glist(char *a);

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

  snprintf(dl->help, MAX_COMMAND_HELP_LEN,
	   "/msg %s GLIST [*pattern*]\nList current G-lines on the network.\n", BOT_NAME);
  snprintf(dl->summary, MAX_COMMAND_SUMMARY_LEN,
	   "List all current G-lines");
  dl->level = 950;
#if 0
  dl->func = m_glist;
#else
  dl->func = (void (*)(char*)) DL_sym(dl->val, "m_glist");
#endif
  return 1;
}

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

MODULE_PUBLIC void m_glist(char *a)
{
  int i, nr=0;
  int have_pattern = 0;
  char tmp[256];
  char time_str[256];
  struct dbaseuser *db;
  struct gline *gp;
  struct dbaseuser *d;
  struct tm *tm_;
  char match_str[101];
  ListElem *el;
  db = sender_au->dbuser;
  if(db) {
    log("From: %s glist [%s]\n", db->nick, a);
  } else
    return;
  if(!is_oper()) {
    say_sender("You are not an Oper.");
    log("To: %s Is not an Oper\n", db->nick);
    return;
  }

  i = 0;
  strncpy(match_str, getword(a,&i), 100);
  match_str[100] = '\0';
  if(strlen(match_str)) {
    have_pattern = 1;
  }

  el = GetHead(gline_list);
  i = 0;
  while(el) {
    i++;
    gp = (struct gline *)(el->data);
    if(have_pattern) {
      if(match(match_str, gp->gline) != 0) {
	el = GetSucc(el);
	continue;
      } else {
	nr++;
      }
    } else {
      nr++;
    }
    d = finduserfromid(gp->placedby);
    if(d) {
      tm_ = localtime(&gp->expire);
      strftime(time_str, 60, "%c", tm_);
      sprintf(tmp, "#%2d: %s expires %s", i, gp->gline, time_str);
      say_sender(tmp);
      sprintf(tmp, "\tby %s reason: %s", d->nick, gp->reason);
      say_sender(tmp);
    } else {
      tm_ = localtime(&gp->expire);
      strftime(time_str, 60, "%c", tm_);
      sprintf(tmp, "#%2d: %s expires %s", i, gp->gline, time_str);
      say_sender(tmp);
      sprintf(tmp, "\tby %s reason: %s", "???", gp->reason);
      say_sender(tmp);
    }
    el = GetSucc(el);
  }
  if(i == 0) {
    say_sender("No G-lines found");
  } else {
    say_sender_("%d (out of %d) G-lines matched your search", nr, i);
  }
  return;
}
