/****************************************************************************
 * 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 "./mdataclient.h"

#include "aqhome/msg/ipc/m_ipc.h"
#include "aqhome/msg/ipc/data/m_ipcd.h"

#include <aqcgi/service/module.h>

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



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

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

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

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

void AQH_ModDataClient_Extend(AQCGI_MODULE *m, AQCGI_SERVICE *sv, const char *baseFolder)
{

  AQH_ModService_Extend(m, sv, baseFolder);
}



void AQH_ModDataClient_HandleRequest(AQCGI_MODULE *m,
                                     AQCGI_REQUEST *rq,
                                     AQCGI_SESSION *session,
                                     AQH_MODDATACLIENT_RUN_FN runFn,
                                     GWEN_BUFFER *dbuf)
{
  AQH_EVENT_LOOP *eventLoop;
  AQH_DATACLIENT *dc;
  int rv;

  rv=AQH_Init();
  if (rv<0) {
    DBG_ERROR(NULL, "here (%d)", rv);
    AQCGI_Request_SetResponseCode(rq, 500);
    AQCGI_Request_SetResponseText(rq, "Internal Error");
    return;
  }

  eventLoop=AQH_EventLoop_new();
  dc=AQH_DataClient_new(eventLoop, AQH_IPC_PROTOCOL_DATA_ID, AQH_IPC_PROTOCOL_DATA_VERSION);
  rv=AQH_DataClient_ReadConfigFile(dc);
  if (rv<0) {
    DBG_ERROR(NULL, "here (%d)", rv);
    AQCGI_Request_SetResponseCode(rq, 500);
    AQCGI_Request_SetResponseText(rq, "Internal Error");
    return;
  }

  rv=AQH_DataClient_ConnectWithArgs(dc, 0);
  if (rv<0) {
    DBG_ERROR(NULL, "Error connecting (%d)", rv);
    AQH_DataClient_free(dc);
    AQH_EventLoop_free(eventLoop);
    AQCGI_Request_SetResponseCode(rq, 500);
    AQCGI_Request_SetResponseText(rq, "Internal Error");
    return;
  }

  if (runFn)
    runFn(m, rq, session, dc, dbuf);

  AQH_DataClient_free(dc);
  AQH_EventLoop_free(eventLoop);

  AQH_Fini();
}



