/****************************************************************************
 * 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

//#define DISABLE_DEBUGLOG


#include "./service_file_p.h"

#include <gwenhywfar/misc.h>
#include <gwenhywfar/debug.h>



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

#define AQH_SERVICE_FILE_GROUP_USERS    "users"
#define AQH_SERVICE_FILE_GROUP_MODULES  "modules"
#define AQH_SERVICE_FILE_GROUP_SESSIONS "sessions"


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

GWEN_INHERIT(AQCGI_SERVICE, AQH_SERVICE_FILE)



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

static void GWENHYWFAR_CB _freeData(void *bp, void *p);

static AQCGI_USER *_loadUser(AQCGI_SERVICE *sv, const char *s);
static int _saveUser(AQCGI_SERVICE *sv, AQCGI_USER *user);
static int _addUser(AQCGI_SERVICE *sv, AQCGI_USER *user);
static int _delUser(AQCGI_SERVICE *sv, const char *s);
static GWEN_STRINGLIST *_listUsers(AQCGI_SERVICE *sv);

static AQCGI_MODULE *_loadModule(AQCGI_SERVICE *sv, const char *s);
static int _saveModule(AQCGI_SERVICE *sv, AQCGI_MODULE *module);
static int _addModule(AQCGI_SERVICE *sv, AQCGI_MODULE *module);
static int _delModule(AQCGI_SERVICE *sv, const char *s);
static GWEN_STRINGLIST *_listModules(AQCGI_SERVICE *sv);

static AQCGI_SESSION* _loadSession(AQCGI_SERVICE *sv, const char *s);
static int _saveSession(AQCGI_SERVICE *sv, AQCGI_SESSION *session);
static int _addSession(AQCGI_SERVICE *sv, AQCGI_SESSION *session);
static int _delSession(AQCGI_SERVICE *sv, const char *s);
static GWEN_STRINGLIST *_listSessions(AQCGI_SERVICE *sv);

static GWEN_DB_NODE *_loadGroupLocked(AQCGI_SERVICE *sv, const char *groupName, const char *subGroupName);
static int _saveGroupLocked(AQCGI_SERVICE *sv, const char *groupName, const char *subGroupName, GWEN_DB_NODE *db);
static int _addGroupLocked(AQCGI_SERVICE *sv, const char *groupName, const char *subGroupName, GWEN_DB_NODE *db);
static int _deleteGroup(AQCGI_SERVICE *sv, const char *groupName, const char *subGroupName);
static GWEN_STRINGLIST *_listGroup(AQCGI_SERVICE *sv, const char *groupName);

//static void _logGroup(const char *groupName, const char *subGroupName, GWEN_DB_NODE *db);



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

AQCGI_SERVICE *AQH_ServiceFiles_new(const char *baseFolder, const char *baseUrl)
{
  AQCGI_SERVICE *sv;
  AQH_SERVICE_FILE *xs;
  GWEN_BUFFER *dbuf;

  sv=AQCGI_Service_new(baseFolder, baseUrl);
  GWEN_NEW_OBJECT(AQH_SERVICE_FILE, xs);
  GWEN_INHERIT_SETDATA(AQCGI_SERVICE, AQH_SERVICE_FILE, sv, xs, _freeData);

  AQCGI_Service_SetLoadUserFn(sv, _loadUser);
  AQCGI_Service_SetSaveUserFn(sv, _saveUser);
  AQCGI_Service_SetAddUserFn(sv, _addUser);
  AQCGI_Service_SetDelUserFn(sv, _delUser);
  AQCGI_Service_SetListUsersFn(sv, _listUsers);

  AQCGI_Service_SetLoadModuleFn(sv, _loadModule);
  AQCGI_Service_SetSaveModuleFn(sv, _saveModule);
  AQCGI_Service_SetAddModuleFn(sv, _addModule);
  AQCGI_Service_SetDelModuleFn(sv, _delModule);
  AQCGI_Service_SetListModulesFn(sv, _listModules);

  AQCGI_Service_SetLoadSessionFn(sv, _loadSession);
  AQCGI_Service_SetSaveSessionFn(sv, _saveSession);
  AQCGI_Service_SetAddSessionFn(sv, _addSession);
  AQCGI_Service_SetDelSessionFn(sv, _delSession);
  AQCGI_Service_SetListSessionsFn(sv, _listSessions);

  dbuf=GWEN_Buffer_new(0, 256, 0, 1);
  GWEN_Buffer_AppendArgs(dbuf, "dir://%s", AQCGI_Service_GetRuntimeFolder(sv));
  DBG_ERROR(NULL, "Creating config mgr \"%s\"", GWEN_Buffer_GetStart(dbuf));
  xs->configMgr=GWEN_ConfigMgr_Factory(GWEN_Buffer_GetStart(dbuf));
  if (xs->configMgr==NULL) {
    DBG_ERROR(NULL, "Error creating config mgr \"%s\"", GWEN_Buffer_GetStart(dbuf));
    GWEN_Buffer_free(dbuf);
    AQCGI_Service_free(sv);
    return NULL;
  }
  GWEN_Buffer_free(dbuf);

  return sv;
}



void GWENHYWFAR_CB _freeData(GWEN_UNUSED void *bp, void *p)
{
  AQH_SERVICE_FILE *xs;

  xs=(AQH_SERVICE_FILE*) p;
  GWEN_ConfigMgr_free(xs->configMgr);
  GWEN_FREE_OBJECT(xs);
}



AQCGI_USER *_loadUser(AQCGI_SERVICE *sv, const char *s)
{
  GWEN_DB_NODE *db;

  db=_loadGroupLocked(sv, AQH_SERVICE_FILE_GROUP_USERS, s);
  if (db) {
    AQCGI_USER *user;

    user=AQCGI_User_fromDb(db);
    GWEN_DB_Group_free(db);
    return user;
  }

  return NULL;
}



int _saveUser(AQCGI_SERVICE *sv, AQCGI_USER *user)
{
  const char *s;

  s=AQCGI_User_GetAlias(user);
  if (s && *s) {
    GWEN_DB_NODE *db;
    int rv;

    db=GWEN_DB_Group_new(s);
    rv=AQCGI_User_toDb(user, db);
    if (rv<0) {
      DBG_ERROR(NULL, "here (%d)", rv);
      GWEN_DB_Group_free(db);
      return rv;
    }

    rv=_saveGroupLocked(sv, AQH_SERVICE_FILE_GROUP_USERS, s, db);
    if (rv<0) {
      DBG_ERROR(NULL, "here (%d)", rv);
      GWEN_DB_Group_free(db);
      return rv;
    }
    GWEN_DB_Group_free(db);
    return 0;
  }
  return GWEN_ERROR_INVALID;
}



int _addUser(AQCGI_SERVICE *sv, AQCGI_USER *user)
{
  const char *s;

  s=AQCGI_User_GetAlias(user);
  if (s && *s) {
    GWEN_DB_NODE *db;
    int rv;

    db=GWEN_DB_Group_new(s);
    rv=AQCGI_User_toDb(user, db);
    if (rv<0) {
      DBG_ERROR(NULL, "here (%d)", rv);
      GWEN_DB_Group_free(db);
      return rv;
    }
    rv=_addGroupLocked(sv, AQH_SERVICE_FILE_GROUP_USERS, s, db);
    if (rv<0) {
      DBG_ERROR(NULL, "here (%d)", rv);
      GWEN_DB_Group_free(db);
      return rv;
    }
    GWEN_DB_Group_free(db);
    return 0;
  }
  else {
    DBG_ERROR(NULL, "Missing alias");
  }
  return GWEN_ERROR_INVALID;
}



int _delUser(AQCGI_SERVICE *sv, const char *s)
{
  return _deleteGroup(sv, AQH_SERVICE_FILE_GROUP_USERS, s);
}



GWEN_STRINGLIST *_listUsers(AQCGI_SERVICE *sv)
{
  return _listGroup(sv, AQH_SERVICE_FILE_GROUP_USERS);
}



AQCGI_MODULE *_loadModule(AQCGI_SERVICE *sv, const char *s)
{
  GWEN_DB_NODE *db;

  db=_loadGroupLocked(sv, AQH_SERVICE_FILE_GROUP_MODULES, s);
  if (db) {
    AQCGI_MODULE *module;

    module=AQCGI_Module_fromDb(db);
    GWEN_DB_Group_free(db);
    return module;
  }

  return NULL;
}



int _saveModule(AQCGI_SERVICE *sv, AQCGI_MODULE *module)
{
  const char *s;

  s=AQCGI_Module_GetName(module);
  if (s && *s) {
    GWEN_DB_NODE *db;
    int rv;

    db=GWEN_DB_Group_new(s);
    rv=AQCGI_Module_toDb(module, db);
    if (rv<0) {
      DBG_ERROR(NULL, "here (%d)", rv);
      GWEN_DB_Group_free(db);
      return rv;
    }
    rv=_saveGroupLocked(sv, AQH_SERVICE_FILE_GROUP_MODULES, s, db);
    if (rv<0) {
      DBG_ERROR(NULL, "here (%d)", rv);
      GWEN_DB_Group_free(db);
      return rv;
    }
    GWEN_DB_Group_free(db);
    return 0;
  }
  return GWEN_ERROR_INVALID;
}



int _addModule(AQCGI_SERVICE *sv, AQCGI_MODULE *module)
{
  const char *s;

  s=AQCGI_Module_GetName(module);
  if (s && *s) {
    GWEN_DB_NODE *db;
    int rv;

    db=GWEN_DB_Group_new(s);
    rv=AQCGI_Module_toDb(module, db);
    if (rv<0) {
      DBG_ERROR(NULL, "here (%d)", rv);
      GWEN_DB_Group_free(db);
      return rv;
    }
    rv=_addGroupLocked(sv, AQH_SERVICE_FILE_GROUP_MODULES, s, db);
    if (rv<0) {
      DBG_ERROR(NULL, "here (%d)", rv);
      GWEN_DB_Group_free(db);
      return rv;
    }
    GWEN_DB_Group_free(db);
    return 0;
  }
  return GWEN_ERROR_INVALID;
}



int _delModule(AQCGI_SERVICE *sv, const char *s)
{
  return _deleteGroup(sv, AQH_SERVICE_FILE_GROUP_MODULES, s);
}



GWEN_STRINGLIST *_listModules(AQCGI_SERVICE *sv)
{
  return _listGroup(sv, AQH_SERVICE_FILE_GROUP_MODULES);
}




AQCGI_SESSION* _loadSession(AQCGI_SERVICE *sv, const char *s)
{
  GWEN_DB_NODE *db;

  db=_loadGroupLocked(sv, AQH_SERVICE_FILE_GROUP_SESSIONS, s);
  if (db) {
    AQCGI_SESSION *session;

    session=AQCGI_Session_fromDb(db);
    GWEN_DB_Group_free(db);
    return session;
  }

  return NULL;
}



int _saveSession(AQCGI_SERVICE *sv, AQCGI_SESSION *session)
{
  const char *s;

  s=AQCGI_Session_GetUid(session);
  if (s && *s) {
    GWEN_DB_NODE *db;
    int rv;

    db=GWEN_DB_Group_new(s);
    rv=AQCGI_Session_toDb(session, db);
    if (rv<0) {
      DBG_ERROR(NULL, "here (%d)", rv);
      GWEN_DB_Group_free(db);
      return rv;
    }
    rv=_saveGroupLocked(sv, AQH_SERVICE_FILE_GROUP_SESSIONS, s, db);
    if (rv<0) {
      DBG_ERROR(NULL, "here (%d)", rv);
      GWEN_DB_Group_free(db);
      return rv;
    }
    GWEN_DB_Group_free(db);
    return 0;
  }
  return GWEN_ERROR_INVALID;
}



int _addSession(AQCGI_SERVICE *sv, AQCGI_SESSION *session)
{
  const char *s;

  s=AQCGI_Session_GetUid(session);
  if (s && *s) {
    GWEN_DB_NODE *db;
    int rv;

    db=GWEN_DB_Group_new(s);
    rv=AQCGI_Session_toDb(session, db);
    if (rv<0) {
      DBG_ERROR(NULL, "here (%d)", rv);
      GWEN_DB_Group_free(db);
      return rv;
    }
    rv=_addGroupLocked(sv, AQH_SERVICE_FILE_GROUP_SESSIONS, s, db);
    if (rv<0) {
      DBG_ERROR(NULL, "here (%d)", rv);
      GWEN_DB_Group_free(db);
      return rv;
    }
    GWEN_DB_Group_free(db);
    return 0;
  }
  return GWEN_ERROR_INVALID;
}



int _delSession(AQCGI_SERVICE *sv, const char *s)
{
  return _deleteGroup(sv, AQH_SERVICE_FILE_GROUP_SESSIONS, s);
}



GWEN_STRINGLIST *_listSessions(AQCGI_SERVICE *sv)
{
  return _listGroup(sv, AQH_SERVICE_FILE_GROUP_SESSIONS);
}



GWEN_DB_NODE *_loadGroupLocked(AQCGI_SERVICE *sv, const char *groupName, const char *subGroupName)
{
  DBG_ERROR(NULL, "Lock and load group %s/%s", groupName, subGroupName);
  if (sv && groupName && subGroupName) {
    AQH_SERVICE_FILE *xs;

    xs=GWEN_INHERIT_GETDATA(AQCGI_SERVICE, AQH_SERVICE_FILE, sv);
    if (xs) {
      GWEN_DB_NODE *db=NULL;
      int rv;

      DBG_ERROR(NULL, "Locking group %s/%s", groupName, subGroupName);
      rv=GWEN_ConfigMgr_LockGroup(xs->configMgr, groupName, subGroupName);
      if (rv<0) {
	DBG_ERROR(NULL, "Error locking group \"%s/%s\": %d", groupName, subGroupName, rv);
	return NULL;
      }
      DBG_ERROR(NULL, "Loading group %s/%s", groupName, subGroupName);
      rv=GWEN_ConfigMgr_GetGroup(xs->configMgr, groupName, subGroupName, &db);
      if (rv<0) {
	DBG_ERROR(NULL, "Error reading group \"%s/%s\": %d", groupName, subGroupName, rv);
	GWEN_ConfigMgr_UnlockGroup(xs->configMgr, groupName, subGroupName);
	return NULL;
      }
      DBG_ERROR(NULL, "Unlocking group %s/%s", groupName, subGroupName);
      rv=GWEN_ConfigMgr_UnlockGroup(xs->configMgr, groupName, subGroupName);
      if (rv<0) {
	DBG_ERROR(NULL, "Error unlocking group \"%s/%s\": %d", groupName, subGroupName, rv);
	GWEN_DB_Group_free(db);
	return NULL;
      }
      return db;
    }
  }
  else {
    DBG_ERROR(NULL, "Missing argument");
  }
  return NULL;
}



int _saveGroupLocked(AQCGI_SERVICE *sv, const char *groupName, const char *subGroupName, GWEN_DB_NODE *db)
{
  if (sv && groupName && subGroupName && db) {
    AQH_SERVICE_FILE *xs;

    xs=GWEN_INHERIT_GETDATA(AQCGI_SERVICE, AQH_SERVICE_FILE, sv);
    if (xs) {
      int rv;

      DBG_ERROR(NULL, "Locking group %s/%s", groupName, subGroupName);
      rv=GWEN_ConfigMgr_LockGroup(xs->configMgr, groupName, subGroupName);
      if (rv<0) {
	DBG_ERROR(NULL, "Error locking group \"%s/%s\": %d", groupName, subGroupName, rv);
	return rv;
      }

      DBG_ERROR(NULL, "Writing group %s/%s", groupName, subGroupName);
      rv=GWEN_ConfigMgr_SetGroup(xs->configMgr, groupName, subGroupName, db);
      if (rv<0) {
	DBG_ERROR(NULL, "Error writing group \"%s/%s\": %d", groupName, subGroupName, rv);
	return rv;
      }

      DBG_ERROR(NULL, "Unlocking group %s/%s", groupName, subGroupName);
      rv=GWEN_ConfigMgr_UnlockGroup(xs->configMgr, groupName, subGroupName);
      if (rv<0) {
	DBG_ERROR(NULL, "Error unlocking group \"%s/%s\": %d", groupName, subGroupName, rv);
	return rv;
      }

      return 0;
    }
  }
  return GWEN_ERROR_INVALID;
}



int _addGroupLocked(AQCGI_SERVICE *sv, const char *groupName, const char *subGroupName, GWEN_DB_NODE *db)
{
  if (sv && groupName && subGroupName && db) {
    AQH_SERVICE_FILE *xs;

    xs=GWEN_INHERIT_GETDATA(AQCGI_SERVICE, AQH_SERVICE_FILE, sv);
    if (xs) {
      int rv;

      rv=GWEN_ConfigMgr_HasGroup(xs->configMgr, groupName, subGroupName);
      if (rv>=0) {
	DBG_ERROR(NULL, "Group \"%s/%s\" already exists", groupName, subGroupName);
	return GWEN_ERROR_FOUND;
      }

      rv=GWEN_ConfigMgr_LockGroup(xs->configMgr, groupName, subGroupName);
      if (rv<0) {
	DBG_ERROR(NULL, "Error locking group \"%s/%s\": %d", groupName, subGroupName, rv);
	return rv;
      }

      rv=GWEN_ConfigMgr_SetGroup(xs->configMgr, groupName, subGroupName, db);
      if (rv<0) {
	DBG_ERROR(NULL, "Error writing group \"%s/%s\": %d", groupName, subGroupName, rv);
	return rv;
      }

      rv=GWEN_ConfigMgr_UnlockGroup(xs->configMgr, groupName, subGroupName);
      if (rv<0) {
	DBG_ERROR(NULL, "Error unlocking group \"%s/%s\": %d", groupName, subGroupName, rv);
	return rv;
      }

      return 0;
    }
  }
  return GWEN_ERROR_INVALID;
}



int _deleteGroup(AQCGI_SERVICE *sv, const char *groupName, const char *subGroupName)
{
  if (sv && groupName && subGroupName) {
    AQH_SERVICE_FILE *xs;

    xs=GWEN_INHERIT_GETDATA(AQCGI_SERVICE, AQH_SERVICE_FILE, sv);
    if (xs) {
      int rv;

      rv=GWEN_ConfigMgr_DeleteGroup(xs->configMgr, groupName, subGroupName);
      if (rv<0) {
	DBG_ERROR(NULL, "Error writing group \"%s/%s\": %d", groupName, subGroupName, rv);
	return rv;
      }
      return 0;
    }
  }
  return GWEN_ERROR_INVALID;
}



GWEN_STRINGLIST *_listGroup(AQCGI_SERVICE *sv, const char *groupName)
{
  if (sv && groupName) {
    AQH_SERVICE_FILE *xs;

    xs=GWEN_INHERIT_GETDATA(AQCGI_SERVICE, AQH_SERVICE_FILE, sv);
    if (xs) {
      GWEN_STRINGLIST *sl;
      int rv;

      sl=GWEN_StringList_new();
      rv=GWEN_ConfigMgr_ListSubGroups(xs->configMgr, groupName, sl);
      if (rv<0) {
	DBG_ERROR(NULL, "Error listing group \"%s\": %d", groupName, rv);
	GWEN_StringList_free(sl);
	return NULL;
      }
      if (GWEN_StringList_Count(sl)==0) {
	GWEN_StringList_free(sl);
	return NULL;
      }
      return sl;
    }
  }
  return NULL;
}



#if 0
void _logGroup(const char *groupName, const char *subGroupName, GWEN_DB_NODE *db)
{
  if (db) {
    GWEN_BUFFER *dbuf;

    dbuf=GWEN_Buffer_new(0, 256, 0, 1);
    GWEN_DB_WriteToBuffer(db, dbuf, GWEN_DB_FLAGS_DEFAULT);
    DBG_ERROR(NULL, "Group %s/%s:\n%s", groupName?groupName:"<empty>", subGroupName?subGroupName:"<empty>",
              GWEN_Buffer_GetStart(dbuf));
    GWEN_Buffer_free(dbuf);
  }
  else {
    DBG_ERROR(NULL, "Group %s/%s empty", groupName?groupName:"<empty>", subGroupName?subGroupName:"<empty>");
  }
}
#endif



