#include <X11/Intrinsic.h>
#include <X11/StringDefs.h>
#include <X11/Xaw/AsciiText.h>
#include <X11/Xaw/AsciiSrc.h>
#include <X11/Xaw/Label.h>
#include <ctype.h>

#include "xznol.h"
#include "file.h"
#include "util.h"

static XContext ntable = 0;

/*ARGSUSED*/
static void unhash(Widget w, XtPointer client, XtPointer call)
{
   XDeleteContext(XtDisplay(w), (XID) w, ntable);
}

Widget make_adduser_text(Widget parent, char *name, table *table)
{
   Widget w;

   if (table) {
      w = XtVaCreateManagedWidget(name, asciiTextWidgetClass, parent,
				  XtNtype, XawAsciiString,
				  NULL);

      if (ntable == 0) ntable = XUniqueContext();
      if (XSaveContext(XtDisplay(w), (XID) w, ntable, (caddr_t) table))
	 abort();

      XtAddCallback(w, XtNdestroyCallback, unhash, NULL);
   } else {
      w = XtVaCreateManagedWidget(name, labelWidgetClass, parent,
				  XtNlabel, "Can't find appropriate table",
				  NULL);
   }

   return(w);
}

/* widget should be a text widget containing the user's name */

void create_user(Widget w, int save)
{
   char *str;
   char name[BUFSIZ];
   int i;
   table *t;

   /* find the table */

   if (XFindContext(XtDisplay(w), (XID) w, ntable, (caddr_t *) &t) == 0) {

      /* find the username */

      XtVaGetValues(XawTextGetSource(w), XtNstring, &str, NULL);

      for (i=0; !isspace(str[i]); i++)
	 name[i] = str[i];
      name[i] = '\0';

      /* create the user */

      add_user(t, strdup(name), NULL);

      if (save)
	 save_newuser(t, name);

      XawAsciiSourceFreeString(XawTextGetSource(w));
   }
}
