/*
 * chantype.c
 * (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 <ctype.h>
#include <stdlib.h>
#include <string.h>

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


char *get_chantype_name(int id)
{
	ListElem *el;
	el = GetHead(chantype_list);
	while (el) {
		ct = (struct chantype *) el->data;
		if (ct->id = id) {
			return ct->name;
		}
		el = GetSucc(el);
	}
	return NULL;
}


struct chantype *chantype_add(char *chantype, char *duration, char *reason, int placedby)
{
	long durationl;
	time_t t;
	struct chantype *g, *ct;
	ListElem *el;
	int already_exist = 0;
	int rlen;

	if (!chantype)
		return 0;
	if (!duration)
		return 0;
	if (!reason)
		return 0;

	g = (struct chantype *) Malloc(sizeof(struct chantype));
	if (!g)
		return 0;
	rlen = MIN(strlen(reason), REASONLEN);
	g->reason = (char *) Malloc(rlen + 1);
	if (!g->reason) {
		Free(g);
		return 0;
	}
	strncpy(g->reason, reason, rlen);
	g->reason[rlen] = '\0';
#if DEBUG
	printf("chantype_add: [%s] [%s] [%s]\n", chantype, duration, reason);
#endif
	strncpy(g->chantype, chantype, CHANTYPELEN);
	g->chantype[CHANTYPELEN] = '\0';
	t = time(NULL);
	durationl = atol(duration);
	g->duration = durationl;
	t += durationl;
	g->expire = t;
	g->placedby = placedby;

	el = GetHead(chantype_list);
	already_exist = 0;
	while (el) {
		ct = (struct chantype *) (el->data);
		if (!strcasecmp(ct->chantype, g->chantype)) {
			already_exist = 1;
			break;
		}
		el = GetSucc(el);
	}
	if (already_exist) {
		Free(g->reason);
		Free(g);
		return 0;
	} else {
		el = NewElem(g);
		AddTail(chantype_list, el);
	}
	return g;
}


int chantype_del(char *chantype)
{
	struct chantype *ct;
	ListElem *el;

	if (!chantype)
		return -1;

#if DEBUG
	printf("chantype_del: [%s]\n", chantype);
	log("chantype_del: [%s]\n", chantype);
#endif

	el = GetHead(chantype_list);
	while (el) {
		ct = (struct chantype *) (el->data);
		if (!strcasecmp(ct->name, chantype)) {
			break;
		}
		el = GetSucc(el);
	}
	if (!el) {
		/* not found */
		return 0;
	}

	Free(ct->name);
	Remove(el);
	FreeElem(el);
	return 1;
}
