/*
 * lchans.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"

#define UNKNOWN_OWNER "\02???\02"

void m_lchans(char *a);

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

  snprintf(dl->help, MAX_COMMAND_HELP_LEN,
	   "Lists all the channels that the bot is currently holding.\n"\
	   "/msg %s LCHANS           List all channels\n"\
	   "/msg %s LCHANS [string]  List only channels including sub-string",
	   BOT_NAME, BOT_NAME);
  snprintf(dl->summary, MAX_COMMAND_SUMMARY_LEN,
	   "Gives a list of all the channels the bot is holding");
  dl->level = 900;
#if 0
  dl->func = m_lchans;
#else
  dl->func = (void (*)(char*)) DL_sym(dl->val, "m_lchans");
#endif
  return 1;
}

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

MODULE_PUBLIC void m_lchans(char *a)
{
  struct chanopts *c;
  struct dbaseuser *owner_d;
  int nr_chans = 0;
  char buffer[512];
  char channel[CHANNELLEN+1];
  char *owner_str;
  char none[10];
  ListElem *el;
  int i;

  struct dbaseuser *db;
  db = sender_au->dbuser;
  if(db) {
    log("From: %s lchans\n", db->nick);
  } 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(channel,getword(a,&i),CHANNELLEN);
  channel[CHANNELLEN] = '\0';

  el = GetHead(channel_list);
  if(strlen(channel)) {
    while(el) {
      c = (struct chanopts *)el->data;
      if(!match(channel, c->channel)) {
	owner_d = finduserfromid(c->owner);
	if(owner_d) {
	  owner_str = owner_d->nick;
	} else {
	  strcpy(none, UNKNOWN_OWNER);
	  owner_str = none;
	}
	sprintf(buffer,"%-15s : Users: %d Founder: %-15s Topic: %s",
		c->channel, c->current_joined, owner_str, c->topic);
	say_sender(buffer);
	nr_chans++;
      }
      el = GetSucc(el);
    }
  } else {
    while(el) {
      c = (struct chanopts *)el->data;
      owner_d = finduserfromid(c->owner);
      if(owner_d) {
	owner_str = owner_d->nick;
      } else {
	strcpy(none, UNKNOWN_OWNER);
	owner_str = none;
      }
      sprintf(buffer,"%-15s : Users: %d Founder: %-15s Topic: %s",
	      c->channel, c->current_joined, owner_str, c->topic);
      say_sender(buffer);
      nr_chans++;
      el = GetSucc(el);
    }
  }
  sprintf(buffer, "%d channels found.", nr_chans);
  say_sender(buffer);
  return;
}

