/*
 * find.c
 * (C) James Craig 1998, Email: jcraig@mad.scientist.com
 * (C) Christian Magnusson 1999, Email: d1mag@dtek.chalmers.se
 * This program is copyright, and covered by the Gnu Public License.
 * The Q bot.
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

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


dl_command_entry_t *findcommand(char *cmd)
{
	ListElem *el = Find(commands, cmd, compare_strcasecmp);
	if (el) {
		return (dl_command_entry_t *) el->data;
	}
	return NULL;
}

struct chanopts *findchannel(char *channel)
{
	ListElem *el = Find(channels, channel, compare_strcasecmp);
	if (el) {
		return (struct chanopts *) el->data;
	}
	return NULL;
}

struct activeuser *nick_to_yxx(char *nick, char *tmp)
{
	struct activeuser *u;
	ListElem *el = Find(auser_nick, nick, compare_strcasecmp);
	if (el) {
		u = (struct activeuser *) el->data;
		strncpy(tmp, u->yxx, YXXLEN);
		tmp[YXXLEN] = '\0';
		return u;
	}
	tmp[0] = 0;
	return NULL;
}

struct activeuser *find_yxx(char *yxx)
{
	int len = 0;
	char yxx2[YXXLEN + 1];
	char *pyxx = NULL;
	ListElem *el;

	if (!yxx)
		return NULL;
	len = strlen(yxx);
	/* (fox) Fixing b0rkage again */
	if (len == 3) {
		yxx2[4] = yxx[2];
		yxx2[3] = yxx[1];
		yxx2[1] = yxx[0];
		yxx2[0] = 'A';
		yxx2[2] = 'A';
		yxx2[5] = '\0';
		pyxx = yxx2;
	} else if (len == 5) {
		pyxx = yxx;
	} else {
		return NULL;
	}
	el = Find(auser_yxx, pyxx, compare_strcmp);
	if (el) {
		return (struct activeuser *) el->data;
	}
	return NULL;
}


/*
 * Find active user by nick. Handy for deleting them, checking authentication
 * and so on.
 */
struct activeuser *findauser(char *nick)
{
	ListElem *el = Find(auser_nick, nick, compare_strcasecmp);
	if (el) {
		return (struct activeuser *) el->data;
	}
	return NULL;
}

struct dbaseuser *finduserfromid(int userid)
{
	ListElem *el = Find(dbusers_userid, &userid, compare_int);
	if (el) {
		return (struct dbaseuser *) el->data;
	}
	return NULL;
}

struct dbaseuser *finduserfromname(char *nick)
{
	ListElem *el = Find(dbusers_nick, nick, compare_strcasecmp);
	if (el) {
		return (struct dbaseuser *) el->data;
	}
	return NULL;
}

struct dbaseuser *finduserfromnick(char *nick)
{
	struct activeuser *a = findauser(nick);
	if (!a)
		return NULL;
	if (a->auth) {
		if (a->dbuser) {
			return a->dbuser;
		} else {
			/* should never happen */
			log("ERROR: *** finduserfromnick dbuser==NULL [%s]\n", nick);
			/* return finduserfromid(a->userid); */
		}
	}
	return NULL;
}
