/****************************************************************************
 * This file is part of the project AqHome.
 * AqHome (c) by 2023 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 "./loop_http.h"
#include "./aqhomestorage_p.h"

#include "aqhome/msg/endpoint_tty.h"
#include "aqhome/ipc/endpoint_ipc.h"
#include "aqhome/mqtt/endpoint_mqttc.h"
#include "aqhome/http/endpoint_http.h"
#include "aqhome/http/httpservice_http.h"

#include <gwenhywfar/gwenhywfar.h>
#include <gwenhywfar/text.h>
#include <gwenhywfar/debug.h>
#include <gwenhywfar/endpoint_tcpd.h>
#include <gwenhywfar/endpoint_msgio.h>
#include <gwenhywfar/syncio.h>
#include <gwenhywfar/url.h>

#ifdef HAVE_SYS_TYPES_H
# include <sys/types.h>
#endif

#ifdef HAVE_SYS_STAT_H
# include <sys/stat.h>
#endif

#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <time.h>




/* ------------------------------------------------------------------------------------------------
 * defines
 * ------------------------------------------------------------------------------------------------
 */

//#define I18N(msg) msg
#define I18S(msg) msg



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

static void _handleHttpEndpoint(AQHOME_STORAGE *aqh, GWEN_MSG_ENDPOINT *ep);
static void _handleHttpMsg(AQHOME_STORAGE *aqh, GWEN_MSG_ENDPOINT *ep, const GWEN_MSG *msgReceived);



/* ------------------------------------------------------------------------------------------------
 * implementations
 * ------------------------------------------------------------------------------------------------
 */

void AqHomeStorage_ReadAndHandleHttpMessages(AQHOME_STORAGE *aqh)
{
  if (aqh->httpdEndpoint) {
    GWEN_MSG_ENDPOINT *ep;

    ep=GWEN_MsgEndpoint_Tree2_GetFirstChild(aqh->httpdEndpoint);
    while(ep) {
      _handleHttpEndpoint(aqh, ep);
      ep=GWEN_MsgEndpoint_Tree2_GetNext(ep);
    }
  }
}



void _handleHttpEndpoint(AQHOME_STORAGE *aqh, GWEN_MSG_ENDPOINT *ep)
{
  GWEN_MSG *msg;

  while( (msg=GWEN_MsgEndpoint_TakeFirstReceivedMessage(ep)) ) {
    _handleHttpMsg(aqh, ep, msg);
    GWEN_Msg_free(msg);
  }
}



void _handleHttpMsg(AQHOME_STORAGE *aqh, GWEN_MSG_ENDPOINT *ep, const GWEN_MSG *msgReceived)
{
  GWEN_MSG *msgResponse;

  msgResponse=AQH_HttpService_HandleHttpRequest(aqh->httpService, ep, msgReceived);
  if (msgResponse) {
    DBG_INFO(NULL, "Sending response message");
    GWEN_MsgEndpoint_AddSendMessage(ep, msgResponse);
  }
  else {
    DBG_INFO(NULL, "No response for message");
  }
}




