/****************************************************************************
 * This file is part of the project AqHome.
 * AqHome (c) by 2025 Martin Preuss, all rights reserved.
 *
 * The license for this file can be found in the file COPYING which you
 * should have received along with this file.
 ****************************************************************************/

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif


#include "./musers.h"

#include <aqcgi/service/module.h>

#include <gwenhywfar/debug.h>
#include <gwenhywfar/timestamp.h>
#include <gwenhywfar/text.h>



/* ------------------------------------------------------------------------------------------------
 * defs and enums
 * ------------------------------------------------------------------------------------------------
 */

#define GBAS GWEN_Buffer_AppendString
#define GBAA GWEN_Buffer_AppendArgs



/* ------------------------------------------------------------------------------------------------
 * forward declarations
 * ------------------------------------------------------------------------------------------------
 */

static void _createPermDefList(AQCGI_MODULE *m);
static void _createRoleList(AQCGI_MODULE *m);

static AQCGI_MODULE *_loadSubModule(AQCGI_MODULE *m, AQCGI_REQUEST *rq, AQCGI_SESSION *session, const char *sModuleName);
static int _handleRequest(AQCGI_MODULE *m, AQCGI_REQUEST *rq, AQCGI_SESSION *session, const char *sLastPathElem);
static void _handleRqIndex(AQCGI_MODULE *m, AQCGI_REQUEST *rq, AQCGI_SESSION *session, GWEN_BUFFER *dbuf);
static void _handleRqEditUserGet(AQCGI_MODULE *m, AQCGI_REQUEST *rq, AQCGI_SESSION *session, GWEN_BUFFER *dbuf);
static void _handleRqEditUserPost(AQCGI_MODULE *m, AQCGI_REQUEST *rq, AQCGI_SESSION *session, GWEN_BUFFER *dbuf);
static void _handleRqAddUserGet(AQCGI_MODULE *m, AQCGI_REQUEST *rq, AQCGI_SESSION *session, GWEN_BUFFER *dbuf);
static void _handleRqAddUserPost(AQCGI_MODULE *m, AQCGI_REQUEST *rq, AQCGI_SESSION *session, GWEN_BUFFER *dbuf);

static int _getHighestUserId(const AQCGI_USER_LIST *userList);
static int _modulePermsHasRole(const AQCGI_MODULE_PERMS *modPerms, uint8_t rid);

static void _writeEditUserForm(AQCGI_MODULE *m,
                               const AQCGI_USER *u,
                               const char *sAlias,
                               const char *sUrl,
                               const char *sSubmitText,
                               GWEN_BUFFER *dbuf);
static void _writeUserModRolesToForm(const AQCGI_ROLE_LIST *roles, const AQCGI_MODULE_PERMS *perms, const char *sModName, GWEN_BUFFER *dbuf);

static void _readAllModRolesForUserFromForm(AQCGI_MODULE *m, GWEN_DB_NODE *dbPost, AQCGI_USER *u);
static void _readModRolesFromForm(GWEN_DB_NODE *dbPost,
                                  const AQCGI_ROLE_LIST *roleList,
                                  const char *sPrefix,
                                  AQCGI_MODULE_PERMS *modPerms);

static void _addLabelAndInputToFormTableH(const char *title, const char *name, const char *value, const char *xxtra, GWEN_BUFFER *dbuf);
static void _addUserStateLabelAndSelectionToFormTableH(const char *sTitle, const char *sName, int st, GWEN_BUFFER *dbuf);




/* ------------------------------------------------------------------------------------------------
 * vars
 * ------------------------------------------------------------------------------------------------
 */

static AQH_MODSERVICE_HANDLER_ENTRY _requestTable[]={
  {"index.html",      AQCGI_REQUEST_METHOD_GET,  AQH_MODADMUSERS_PERMS_USERSREAD,  _handleRqIndex},
  {"edituser.html",   AQCGI_REQUEST_METHOD_GET,  AQH_MODADMUSERS_PERMS_USERSWRITE, _handleRqEditUserGet},
  {"edituser.html",   AQCGI_REQUEST_METHOD_POST, AQH_MODADMUSERS_PERMS_USERSWRITE, _handleRqEditUserPost},
  {"adduser.html",    AQCGI_REQUEST_METHOD_GET,  AQH_MODADMUSERS_PERMS_USERSWRITE, _handleRqAddUserGet},
  {"adduser.html",    AQCGI_REQUEST_METHOD_POST, AQH_MODADMUSERS_PERMS_USERSWRITE, _handleRqAddUserPost},
  {NULL, 0, 0, NULL}
};



/* ------------------------------------------------------------------------------------------------
 * code
 * ------------------------------------------------------------------------------------------------
 */

void AQH_ModAdmUsers_Extend(AQCGI_MODULE *m, AQCGI_SERVICE *sv, const char *baseFolder)
{
  AQH_ModService_Extend(m, sv, baseFolder);
  AQH_ModService_SetHandleRequestFn(m, _handleRequest);
  AQH_ModService_SetLoadSubModuleFn(m, _loadSubModule);
}



int AQH_ModAdmUsers_Create(AQCGI_SERVICE *sv)
{
  AQCGI_MODULE *m;
  int rv;

  m=AQCGI_Module_new();
  AQCGI_Module_SetName(m, "users");
  AQCGI_Module_SetDescr(m, "user administration module");
  AQCGI_Module_SetGuestPerms(m, 0);

  _createPermDefList(m);
  _createRoleList(m);

  rv=AQCGI_Service_AddModule(sv, m);
  if (rv<0) {
    DBG_INFO(NULL, "here (%d)", rv);
  }
  AQCGI_Module_free(m);
  return rv;
}



void _createPermDefList(AQCGI_MODULE *m)
{
  AQCGI_PERMDEF_LIST *permDefList;

  permDefList=AQCGI_PermDef_List_new();

  AQH_ModService_AddPermDef(permDefList, "UserRead",  0x001, "Read users");
  AQH_ModService_AddPermDef(permDefList, "UserWrite", 0x002, "Modify users");
  AQH_ModService_AddPermDef(permDefList, "UserAdd",   0x004, "Add users");
  AQH_ModService_AddPermDef(permDefList, "UserDel",   0x008, "Remove users");

  AQCGI_Module_SetPermDefList(m, permDefList);
}



void _createRoleList(AQCGI_MODULE *m)
{
  AQCGI_ROLE_LIST *roleList;
  int id=1;

  roleList=AQCGI_Role_List_new();
  AQH_ModService_AddRole(roleList, id++, "admin",
                         AQH_MODADMUSERS_PERMS_USERSREAD |
                         AQH_MODADMUSERS_PERMS_USERSWRITE |
                         AQH_MODADMUSERS_PERMS_USERSADD |
                         AQH_MODADMUSERS_PERMS_USERSDEL,
                         "Administrator Role");
  AQCGI_Module_SetRoleList(m, roleList);
}



AQCGI_MODULE *_loadSubModule(AQCGI_MODULE *m, AQCGI_REQUEST *rq, AQCGI_SESSION *session, const char *sModuleName)
{
  /* no sub-modules */
  return NULL;
}



int _handleRequest(AQCGI_MODULE *m, AQCGI_REQUEST *rq, AQCGI_SESSION *session, const char *sLastPathElem)
{
  AQH_ModService_HandleRequestWithTable(m, rq, session, sLastPathElem, _requestTable);
  return AQCGI_SendResponse(rq);
}



void _handleRqIndex(AQCGI_MODULE *m, AQCGI_REQUEST *rq, AQCGI_SESSION *session, GWEN_BUFFER *dbuf)
{
  AQCGI_USER_LIST *userList;
  uint32_t perms;

  perms=AQH_ModService_GetUserPerms(m);
  userList=AQH_ModService_LoadRawUsers(m);

  GBAS(dbuf, "<h1>Users</h1>\n");
  GBAS(dbuf,
       "<table class=\"datatable\">\n"
       "<thead>"
       "<tr><th>Id</th><th>Alias</th><th>Name</th><th>Status</th><th>Email</th><th>Notes</th><th>Actions</th></tr>\n"
       "</thead>\n"
       "<tbody>\n");
  if (userList) {
    const AQCGI_USER *u;

    AQCGI_User_List_SortByAlias(userList, 1);
    u=AQCGI_User_List_First(userList);
    while(u) {
      const char *sUserAlias;

      sUserAlias=AQCGI_User_GetAlias(u);
      if (sUserAlias && *sUserAlias) {
        uint32_t id;
        const char *s;
        const char *sAlias;

        id=AQCGI_User_GetId(u);
        sAlias=AQCGI_User_GetAlias(u);
        GBAS(dbuf, "<tr>");
        GBAA(dbuf, "<td>%lu</td>", (unsigned long int) id);
        GBAA(dbuf, "<td>%s</td>", sAlias?sAlias:"");
        s=AQCGI_User_GetName(u);
        GBAA(dbuf, "<td>%s</td>", s?s:"");
        s=AQCGI_UserState_toString(AQCGI_User_GetState(u));
        GBAA(dbuf, "<td>%s</td>", s?s:"");
        s=AQCGI_User_GetEmail(u);
        GBAA(dbuf, "<td>%s</td>", s?s:"");
        s=AQCGI_User_GetNotes(u);
        GBAA(dbuf, "<td>%s</td>", s?s:"");

        GBAS(dbuf, "<td>");
        if (perms & AQH_MODADMUSERS_PERMS_USERSWRITE) {
          DBG_ERROR(NULL, "User=%s", sAlias?sAlias:"");
          GBAS(dbuf, "<a href=\"edituser.html?alias=");
          GWEN_Text_EscapeToBufferTolerant(sAlias?sAlias:"", dbuf);
          GBAS(dbuf, "\"><img src=\"/pics/edit.png\"></a>");
        }
        GBAA(dbuf, "</td>\n");
        GBAA(dbuf, "</tr>\n");
      }
      u=AQCGI_User_List_Next(u);
    }
    GBAS(dbuf,
         "</tbody>\n"
         "</table>\n");
    AQCGI_User_List_free(userList);
  }
  if (perms & AQH_MODADMUSERS_PERMS_USERSADD)
    GBAS(dbuf, "<hr><a href=\"adduser.html\">Add User</a>");
}



void _handleRqEditUserGet(AQCGI_MODULE *m, AQCGI_REQUEST *rq, AQCGI_SESSION *session, GWEN_BUFFER *dbuf)
{
  AQCGI_SERVICE *sv;
  GWEN_DB_NODE *dbQuery;
  const char *sAlias;
  AQCGI_USER *user;

  sv=AQH_ModService_GetService(m);
  dbQuery=AQCGI_Request_GetDbQuery(rq);
  sAlias=dbQuery?GWEN_DB_GetCharValue(dbQuery, "alias", 0, NULL):NULL;
  user=(sAlias && *sAlias)?AQCGI_Service_LoadUser(sv, sAlias):NULL;
  if (user) {
    _writeEditUserForm(m, user, sAlias, "edituser.html", "Save", dbuf);
    AQCGI_User_free(user);
  }
  else {
    AQCGI_Request_AddResponseHeaderData(rq, "Location: index.html");
    AQCGI_Request_SetResponseCode(rq, 303);
    AQCGI_Request_SetResponseText(rq, "See other");
  }
}



void _handleRqEditUserPost(AQCGI_MODULE *m, AQCGI_REQUEST *rq, AQCGI_SESSION *session, GWEN_BUFFER *dbuf)
{
  AQCGI_SERVICE *sv;
  GWEN_DB_NODE *dbPost;
  const char *sAlias;
  AQCGI_USER *u;

  sv=AQH_ModService_GetService(m);
  dbPost=AQCGI_Request_GetDbPostBody(rq);
  sAlias=dbPost?GWEN_DB_GetCharValue(dbPost, "alias", 0, NULL):NULL;
  u=(sAlias && *sAlias)?AQCGI_Service_LoadUser(sv, sAlias):NULL;
  if (u) {
    const char *s;
    int state;
    int rv;

    s=GWEN_DB_GetCharValue(dbPost, "name", 0, NULL);
    AQCGI_User_SetName(u, s);
    s=GWEN_DB_GetCharValue(dbPost, "email", 0, NULL);
    AQCGI_User_SetEmail(u, s);
    s=GWEN_DB_GetCharValue(dbPost, "notes", 0, NULL);
    AQCGI_User_SetNotes(u, s);
    s=GWEN_DB_GetCharValue(dbPost, "status", 0, NULL);
    state=(s && *s)?AQCGI_UserState_fromString(s):AQCGI_UserState_Unknown;
    if (state!=AQCGI_UserState_Unknown)
      AQCGI_User_SetState(u, state);

    _readAllModRolesForUserFromForm(m, dbPost, u);

    rv=AQCGI_Service_SaveUser(sv, u);
    if (rv<0) {
      GBAS(dbuf, "<h2>Error</h2><p>Error saving user</p>");
      DBG_ERROR(NULL, "Could not save user \"%s\"", sAlias);
      AQCGI_User_free(u);
      return;
    }
    DBG_ERROR(NULL, "User \"%s\" saved", sAlias);
    AQCGI_User_free(u);
    AQCGI_Request_AddResponseHeaderData(rq, "Location: index.html");
    AQCGI_Request_SetResponseCode(rq, 303);
    AQCGI_Request_SetResponseText(rq, "See other");
  }
  else {
    DBG_ERROR(NULL, "Could not load user \"%s\"", sAlias?sAlias:"<no name>");
    GBAS(dbuf, "<p>Error loading user.</p>\n");
  }
}



void _handleRqAddUserGet(AQCGI_MODULE *m, AQCGI_REQUEST *rq, AQCGI_SESSION *session, GWEN_BUFFER *dbuf)
{
  DBG_ERROR(NULL, "AddUser");
  _writeEditUserForm(m, NULL, NULL, "adduser.html", "Add", dbuf);
}



void _handleRqAddUserPost(AQCGI_MODULE *m, AQCGI_REQUEST *rq, AQCGI_SESSION *session, GWEN_BUFFER *dbuf)
{
  AQCGI_SERVICE *sv;
  GWEN_DB_NODE *dbPost;
  const char *sAlias;

  sv=AQH_ModService_GetService(m);
  dbPost=AQCGI_Request_GetDbPostBody(rq);
  sAlias=dbPost?GWEN_DB_GetCharValue(dbPost, "alias", 0, NULL):NULL;
  // TODO: check alias validity
  if (sAlias) {
    AQCGI_USER *u;
    const char *s;
    int state;
    int rv;
    uint32_t userId;
    AQCGI_USER_LIST *userList;

    u=AQCGI_User_new();
    userList=AQH_ModService_LoadRawUsers(m);
    userId=_getHighestUserId(userList)+1;
    AQCGI_User_SetId(u, userId);
    AQCGI_User_SetAlias(u, sAlias);
    s=GWEN_DB_GetCharValue(dbPost, "name", 0, NULL);
    AQCGI_User_SetName(u, s);
    s=GWEN_DB_GetCharValue(dbPost, "email", 0, NULL);
    AQCGI_User_SetEmail(u, s);
    s=GWEN_DB_GetCharValue(dbPost, "notes", 0, NULL);
    AQCGI_User_SetNotes(u, s);
    s=GWEN_DB_GetCharValue(dbPost, "status", 0, NULL);
    state=(s && *s)?AQCGI_UserState_fromString(s):AQCGI_UserState_Unknown;
    if (state!=AQCGI_UserState_Unknown)
      AQCGI_User_SetState(u, state);

    rv=AQCGI_Service_AddUser(sv, u);
    if (rv<0) {
      GBAS(dbuf, "<h2>Error</h2><p>Error saving user</p>");
      DBG_ERROR(NULL, "Could not save user \"%s\" (%d)", sAlias, rv);
      AQCGI_User_free(u);
      AQCGI_User_List_free(userList);
      return;
    }
    DBG_ERROR(NULL, "User \"%s\" saved", sAlias);
    AQCGI_User_free(u);
    AQH_ModService_Redirect(rq, "index.html");
    AQCGI_User_List_free(userList);
  }
  else {
    DBG_ERROR(NULL, "Missing alias");
    GBAS(dbuf, "<p>Missing alias.</p>\n");
  }
}



int _getHighestUserId(const AQCGI_USER_LIST *userList)
{
  int id=0;

  if (userList) {
    const AQCGI_USER *user;

    user=AQCGI_User_List_First(userList);
    while(user) {
      int uid;

      uid=AQCGI_User_GetId(user);
      id=(uid>id)?uid:id;
      user=AQCGI_User_List_Next(user);
    }
  }
  return id;
}



int _modulePermsHasRole(const AQCGI_MODULE_PERMS *modPerms, uint8_t rid)
{
  if (modPerms) {
    int arraySize;
    int i;

    arraySize=AQCGI_ModulePerms_GetRoleArrayArraySize();
    for(i=0; i<arraySize; i++) {
      if (AQCGI_ModulePerms_GetRoleArrayAt(modPerms, i)==rid)
        return 1;
    }
  }

  return 0;
}





void _writeEditUserForm(AQCGI_MODULE *m,
                        const AQCGI_USER *u,
                        const char *sAlias,
                        const char *sUrl,
                        const char *sSubmitText,
                        GWEN_BUFFER *dbuf)
{
  AQCGI_MODULE_LIST *moduleList;

  /* write user info */
  GBAS(dbuf, "<h2>User Info</h2>\n");
  GBAA(dbuf,
       "<form action=\"%s\" method=\"post\">\n"
       "<table class=\"formtable\">\n",
       sUrl?sUrl:"");
  _addLabelAndInputToFormTableH("Alias", "alias", sAlias,                      "required", dbuf);
  _addLabelAndInputToFormTableH("Name",  "name",  u?AQCGI_User_GetName(u):NULL,  NULL,       dbuf);
  _addLabelAndInputToFormTableH("Email", "email", u?AQCGI_User_GetEmail(u):NULL, NULL,       dbuf);
  _addLabelAndInputToFormTableH("Notes", "notes", u?AQCGI_User_GetNotes(u):NULL, NULL,       dbuf);
  _addUserStateLabelAndSelectionToFormTableH("Status", "status", u?AQCGI_User_GetState(u):AQCGI_UserState_Unknown, dbuf);

  GBAS(dbuf, "</table>\n");

  /* module permissions */
  GBAS(dbuf, "<h2>Module Roles</h2>\n");
    GBAS(dbuf,
         "<table class=\"datatable\">\n"
         "<thead>"
         "<tr><th>Module</th><th>Roles</th></tr>\n"
         "</thead>\n"
         "<tbody>\n");
  moduleList=AQH_ModService_LoadRawModules(m);
  if (moduleList) {
    const AQCGI_MODULE_PERMS_LIST *modPermsList;
    const AQCGI_MODULE *currentMod;

    modPermsList=u?AQCGI_User_GetModulePermList(u):NULL;
    currentMod=AQCGI_Module_List_First(moduleList);
    while(currentMod) {
      const char *sModName;
      const AQCGI_MODULE_PERMS *modPerms;

      sModName=AQCGI_Module_GetName(currentMod);
      GBAA(dbuf, "<tr><td>%s</td><td>", sModName);

      modPerms=modPermsList?AQCGI_ModulePerms_List_GetByModuleId(modPermsList, sModName):NULL;
      _writeUserModRolesToForm(AQCGI_Module_GetRoleList(currentMod), modPerms, sModName, dbuf);
      GBAS(dbuf, "</td></tr>\n");
      GBAS(dbuf, "<td>");

      currentMod=AQCGI_Module_List_Next(currentMod);
    } /* while */
    AQCGI_Module_List_free(moduleList);
  }
  GBAS(dbuf,
       "</tbody>\n"
       "</table>\n");


  GBAA(dbuf, "<input type=\"hidden\" name=\"alias\" value=\"%s\">\n", sAlias?sAlias:"");
  GBAA(dbuf, "<input type=\"submit\" value=\"%s\">\n</form>\n\n", sSubmitText?sSubmitText:"Save");

}



void _readAllModRolesForUserFromForm(AQCGI_MODULE *m, GWEN_DB_NODE *dbPost, AQCGI_USER *u)
{
  AQCGI_MODULE_LIST *moduleList;

  moduleList=AQH_ModService_LoadRawModules(m);
  if (moduleList) {
    AQCGI_MODULE_PERMS_LIST *permsList;
    const AQCGI_MODULE *module;

    permsList=AQCGI_User_GetModulePermList(u);
    if (permsList==NULL) {
      DBG_ERROR(NULL, "Creating module perms list for user");
      permsList=AQCGI_ModulePerms_List_new();
      AQCGI_User_SetModulePermList(u, permsList);
    }

    module=AQCGI_Module_List_First(moduleList);
    while(module) {
      const char *sModName;
      const AQCGI_ROLE_LIST *roleList;

      sModName=AQCGI_Module_GetName(module);
      roleList=AQCGI_Module_GetRoleList(module);
      if (sModName && *sModName && roleList) {
        AQCGI_MODULE_PERMS *modPerms;

        modPerms=AQCGI_ModulePerms_List_GetByModuleId(permsList, sModName);
        if (modPerms==NULL) {
          modPerms=AQCGI_ModulePerms_new();
          AQCGI_ModulePerms_SetModuleId(modPerms, sModName);
          AQCGI_ModulePerms_List_Add(modPerms, permsList);
        }
        _readModRolesFromForm(dbPost, roleList, sModName, modPerms);
      }
      module=AQCGI_Module_List_Next(module);
    }

    AQCGI_Module_List_free(moduleList);
  }
}



void _writeUserModRolesToForm(const AQCGI_ROLE_LIST *roleList, const AQCGI_MODULE_PERMS *modPerms, const char *sModName, GWEN_BUFFER *dbuf)
{
  if (roleList) {
    const AQCGI_ROLE *role;

    role=AQCGI_Role_List_First(roleList);
    while(role) {
      const char *sRoleName;
      uint8_t roleId;

      roleId=AQCGI_Role_GetId(role);
      sRoleName=AQCGI_Role_GetName(role);
      if (sRoleName && *sRoleName) {
        int isChecked;

        isChecked=(modPerms && _modulePermsHasRole(modPerms, roleId));
        if (sModName && *sModName) {
          GBAA(dbuf, "<input type=\"checkbox\" name=\"%s:%s\" %s>", sModName, sRoleName, isChecked?"checked":"");
          GBAA(dbuf, "<label for=\"%s:%s\">%s</label>", sModName, sRoleName, sRoleName);
        }
        else {
          GBAA(dbuf, "<input type=\"checkbox\" name=\"%s\" %s>", sRoleName, isChecked?"checked":"");
          GBAA(dbuf, "<label for=\"%s\">%s</label>", sRoleName, sRoleName);
        }
      }
      role=AQCGI_Role_List_Next(role);
    }
  }
}



void _readModRolesFromForm(GWEN_DB_NODE *dbPost,
                           const AQCGI_ROLE_LIST *roleList,
                           const char *sPrefix,
                           AQCGI_MODULE_PERMS *modPerms)
{
  AQCGI_ModulePerms_PresetRoleArray(modPerms, 0);
  if (roleList) {
    GWEN_BUFFER *tbuf;
    uint32_t pos;
    const AQCGI_ROLE *role;
    int nextRolePos=0;

    tbuf=GWEN_Buffer_new(0, 256, 0, 1);
    if (sPrefix && *sPrefix)
      GBAA(tbuf, "%s:", sPrefix);
    pos=GWEN_Buffer_GetPos(tbuf);

    role=AQCGI_Role_List_First(roleList);
    while(role) {
      const char *roleName;

      roleName=AQCGI_Role_GetName(role);
      if (roleName && *roleName) {
        const char *s;

        GBAS(tbuf, roleName);
        s=GWEN_DB_GetCharValue(dbPost, GWEN_Buffer_GetStart(tbuf), 0, NULL);
        /*DBG_ERROR(NULL, "Role string %s = [%s]", GWEN_Buffer_GetStart(tbuf), s?s:"<empty>");*/
        if (s && *s) {
	  if (nextRolePos<AQCGI_ModulePerms_GetRoleArrayArraySize()) {
            /*DBG_ERROR(NULL, "Setting role \"%s\" (%d)", roleName, AQCGI_Role_GetId(role));*/
	    AQCGI_ModulePerms_SetRoleArrayAt(modPerms, nextRolePos++, AQCGI_Role_GetId(role));
	  }
        }
        GWEN_Buffer_Crop(tbuf, 0, pos);
      }

      role=AQCGI_Role_List_Next(role);
    } /* while */
    GWEN_Buffer_free(tbuf);
  }
}







void _addUserStateLabelAndSelectionToFormTableH(const char *sTitle, const char *sName, int st, GWEN_BUFFER *dbuf)
{
  int i;

  GBAA(dbuf, "<tr><td><label for=\"%s\">%s:</label></td>", sName?sName:"", sTitle?sTitle:"");
  GBAA(dbuf, "<td><select name=\"%s\">", sName?sName:"");
  for(i=AQCGI_UserState_Unknown; i<=AQCGI_UserState_Active; i++) {
    const char *s;

    s=AQCGI_UserState_toString(i);
    GBAA(dbuf, "<option value=\"%s\" %s>%s</option>", s, (i==st)?"selected":"", s);
  }
  GBAS(dbuf, "</select></td></tr>");
}



void _addLabelAndInputToFormTableH(const char *sTitle, const char *sName, const char *sValue, const char *sExtra, GWEN_BUFFER *dbuf)
{
  GBAS(dbuf, "<tr>");
  GBAA(dbuf, "<td><label for=\"%s:\">%s</label></td>", sName?sName:"", sTitle?sTitle:"");
  GBAA(dbuf, "<td><input type=\"text\" name=\"%s\"", sName?sName:"");
  if (sValue && *sValue)
    GBAA(dbuf, " value=\"%s\"", sValue);
  if (sExtra && *sExtra)
    GBAA(dbuf, " %s", sExtra);
  GBAS(dbuf, "></td>");
  GBAS(dbuf, "</tr>\n");
}



