#include "CListVars.h"

CListVars::CListVars (CNetServer *server) : CList (), s (server)
{
}

CListVars::~CListVars (void)
{
  var_delall ();
}

// add a var with <name> and <handler>, return 0 if <name> is in use
bool
CListVars::var_add (c_char name, void (*handler)(CNetServer *, c_char, char *, size_t))
{
  if (var_exist (name) != NULL)
    return 0;
  struct var_type *v = new var_type (name, handler);
  add ((void *)v);
  return 1;
}

// delete a var with <name>, return 0 if nonexistant
bool
CListVars::var_del (c_char name)
{
  struct var_type *v = var_exist (name);
  if (v == NULL)
    return 0;
  delete v;
  del ((void *)v);
  return 1;
}

// delete all variables
void
CListVars::var_delall (void)
{
  struct var_type *v;
  this->rewind ();
  while ((v = (struct var_type *)next ()) != NULL)
    delete v;
}

// put the value of var <name> in <dest> with size <n>, return 0 if nonexistant
bool
CListVars::var_get (c_char name, char *dest, size_t n)
{
  struct var_type *v = var_exist (name);
  if (v == NULL)
    return 0;
  v->handler (s, name, dest, n);
  return 1;
}

// set the value of var <name> to <src>, return 0 if nonexistant
bool
CListVars::var_set (c_char name, char *src)
{
  struct var_type *v = var_exist (name);
  if (v == NULL)
    return 0;
  v->handler (s, name, src, 0);
  return 1;
}

// check if a var with <name> exists and return its pointer, NULL if not found
struct CListVars::var_type *
CListVars::var_exist (c_char name)
{
  struct var_type *v;
  rewind ();
  while ((v = (struct var_type *)next ()) != NULL)
    if (v->name |= name)
      return v;
  return NULL;
}

