/****************************************************************************
 * 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 "./endpoint_p.h"
#include "aqhome/ipc2/msgreader.h"
#include "aqhome/ipc2/msgwriter.h"
#include "aqhome/msg/node/m_node.h"

#include "aqhome/msg/node/m_device.h"
#include "aqhome/msg/node/m_recvstats.h"
#include "aqhome/msg/node/m_sendstats.h"


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



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

/*#define LOG_MESSAGES*/



enum {
  AQH_ENDPOINT_SLOT_MSG_RECVD=1,
  AQH_ENDPOINT_SLOT_MSG_SENT,
  AQH_ENDPOINT_SLOT_CLOSED
};



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

GWEN_INHERIT(AQH_OBJECT, AQH_ENDPOINT)



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

static void GWENHYWFAR_CB _freeData(void *bp, void *p);
static int _handleSignal(AQH_OBJECT *o, uint32_t slotId, AQH_OBJECT *senderObject, int param1, void *param2);
static int _handleMsgRecvd(AQH_OBJECT *o, int msgLen, const uint8_t *msgPtr);
static int _handleMsgSent(AQH_OBJECT *o);
static int _handleClosed(AQH_OBJECT *o);



/* ------------------------------------------------------------------------------------------------
 * implementation
 * ------------------------------------------------------------------------------------------------
 */

AQH_OBJECT *AQH_Endpoint_new(AQH_EVENT_LOOP *eventLoop, AQH_OBJECT *msgReader, AQH_OBJECT *msgWriter)
{
  AQH_OBJECT *o;
  AQH_ENDPOINT *xo;

  o=AQH_Object_new(eventLoop);
  GWEN_NEW_OBJECT(AQH_ENDPOINT, xo);
  GWEN_INHERIT_SETDATA(AQH_OBJECT, AQH_ENDPOINT, o, xo, _freeData);

  xo->msgOutList=AQH_Message_List_new();
  xo->msgInList=AQH_Message_List_new();

  AQH_Object_SetSignalHandlerFn(o, _handleSignal);

  if (msgReader) {
    xo->msgReader=msgReader;
    AQH_Object_AddLink(msgReader, AQH_MSG_READER_SIGNAL_MSGRECVD, AQH_ENDPOINT_SLOT_MSG_RECVD, o);
    AQH_Object_AddLink(msgReader, AQH_MSG_READER_SIGNAL_CLOSED, AQH_ENDPOINT_SLOT_CLOSED, o);
  }

  if (msgWriter) {
    xo->msgWriter=msgWriter;
    AQH_Object_AddLink(msgWriter, AQH_MSG_WRITER_SIGNAL_MSGSENT, AQH_ENDPOINT_SLOT_MSG_SENT, o);
    AQH_Object_AddLink(msgWriter, AQH_MSG_WRITER_SIGNAL_CLOSED,  AQH_ENDPOINT_SLOT_CLOSED, o);
  }

  return o;
}



void GWENHYWFAR_CB _freeData(GWEN_UNUSED void *bp, void *p)
{
  AQH_ENDPOINT *xo;

  xo=(AQH_ENDPOINT*) p;
  free(xo->serviceName);
  free(xo->userName);
  AQH_Message_List_free(xo->msgOutList);
  AQH_Message_List_free(xo->msgInList);
  AQH_Object_free(xo->msgWriter);
  AQH_Object_free(xo->msgReader);
  GWEN_FREE_OBJECT(xo);
}



int AQH_Endpoint_GetApiCode(const AQH_OBJECT *o)
{
  if (o) {
    AQH_ENDPOINT *xo;

    xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQH_ENDPOINT, o);
    if (xo)
      return xo->apiCode;
  }
  return 0;
}



void AQH_Endpoint_SetApiCode(AQH_OBJECT *o, int i)
{
  if (o) {
    AQH_ENDPOINT *xo;

    xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQH_ENDPOINT, o);
    if (xo)
      xo->apiCode=i;
  }
}



const char *AQH_Endpoint_GetServiceName(const AQH_OBJECT *o)
{
  if (o) {
    AQH_ENDPOINT *xo;

    xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQH_ENDPOINT, o);
    if (xo)
      return xo->serviceName;
  }
  return NULL;
}



void AQH_Endpoint_SetServiceName(AQH_OBJECT *o, const char *s)
{
  if (o) {
    AQH_ENDPOINT *xo;

    xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQH_ENDPOINT, o);
    if (xo) {
      free(xo->serviceName);
      xo->serviceName=s?strdup(s):NULL;
    }
  }
}



const char *AQH_Endpoint_GetUserName(const AQH_OBJECT *o)
{
  if (o) {
    AQH_ENDPOINT *xo;

    xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQH_ENDPOINT, o);
    if (xo)
      return xo->userName;
  }
  return NULL;
}



void AQH_Endpoint_SetUserName(AQH_OBJECT *o, const char *s)
{
  if (o) {
    AQH_ENDPOINT *xo;

    xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQH_ENDPOINT, o);
    if (xo) {
      free(xo->userName);
      xo->userName=s?strdup(s):NULL;
    }
  }
}



uint32_t AQH_Endpoint_GetPermissions(const AQH_OBJECT *o)
{
  if (o) {
    AQH_ENDPOINT *xo;

    xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQH_ENDPOINT, o);
    if (xo)
      return xo->permissions;
  }
  return 0;
}



void AQH_Endpoint_SetPermissions(AQH_OBJECT *o, uint32_t i)
{
  if (o) {
    AQH_ENDPOINT *xo;

    xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQH_ENDPOINT, o);
    if (xo)
      xo->permissions=i;
  }
}



void AQH_Endpoint_AddPermissions(AQH_OBJECT *o, uint32_t i)
{
  if (o) {
    AQH_ENDPOINT *xo;

    xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQH_ENDPOINT, o);
    if (xo)
      xo->permissions|=i;
  }
}



void AQH_Endpoint_SubPermissions(AQH_OBJECT *o, uint32_t i)
{
  if (o) {
    AQH_ENDPOINT *xo;

    xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQH_ENDPOINT, o);
    if (xo)
      xo->permissions&=~i;
  }
}



uint32_t AQH_Endpoint_GetFlags(const AQH_OBJECT *o)
{
  if (o) {
    AQH_ENDPOINT *xo;

    xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQH_ENDPOINT, o);
    if (xo)
      return xo->flags;
  }
  return 0;
}



void AQH_Endpoint_SetFlags(AQH_OBJECT *o, uint32_t i)
{
  if (o) {
    AQH_ENDPOINT *xo;

    xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQH_ENDPOINT, o);
    if (xo)
      xo->flags=i;
  }
}



void AQH_Endpoint_AddFlags(AQH_OBJECT *o, uint32_t i)
{
  if (o) {
    AQH_ENDPOINT *xo;

    xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQH_ENDPOINT, o);
    if (xo)
      xo->flags|=i;
  }
}



void AQH_Endpoint_SubFlags(AQH_OBJECT *o, uint32_t i)
{
  if (o) {
    AQH_ENDPOINT *xo;

    xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQH_ENDPOINT, o);
    if (xo)
      xo->flags&=~i;
  }
}



int AQH_Endpoint_GetState(const AQH_OBJECT *o)
{
  if (o) {
    AQH_ENDPOINT *xo;

    xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQH_ENDPOINT, o);
    if (xo)
      return xo->state;
  }
  return 0;
}



void AQH_Endpoint_SetState(AQH_OBJECT *o, int i)
{
  if (o) {
    AQH_ENDPOINT *xo;

    xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQH_ENDPOINT, o);
    if (xo)
      xo->state=i;
  }
}



uint32_t AQH_Endpoint_GetAcceptedMsgGroups(const AQH_OBJECT *o)
{
  if (o) {
    AQH_ENDPOINT *xo;

    xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQH_ENDPOINT, o);
    if (xo)
      return xo->acceptedMsgGroups;
  }
  return 0;
}



void AQH_Endpoint_SetAcceptedMsgGroups(AQH_OBJECT *o, uint32_t i)
{
  if (o) {
    AQH_ENDPOINT *xo;

    xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQH_ENDPOINT, o);
    if (xo)
      xo->acceptedMsgGroups=i;
  }
}



AQH_MESSAGE_LIST *AQH_Endpoint_GetMsgOutList(const AQH_OBJECT *o)
{
  if (o) {
    AQH_ENDPOINT *xo;

    xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQH_ENDPOINT, o);
    if (xo)
      return xo->msgOutList;
  }
  return NULL;
}



AQH_MESSAGE *AQH_Endpoint_GetNextMsgOut(AQH_OBJECT *o)
{
  if (o) {
    AQH_ENDPOINT *xo;

    xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQH_ENDPOINT, o);
    if (xo)
      return AQH_Message_List_First(xo->msgOutList);
  }
  return NULL;
}



void AQH_Endpoint_AddMsgOut(AQH_OBJECT *o, AQH_MESSAGE *msg)
{
  assert(o);
  if (o && msg) {
    AQH_ENDPOINT *xo;

    xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQH_ENDPOINT, o);
    if (xo) {
      if (AQH_Message_GetUsedSize(msg)<1) {
        DBG_ERROR(AQH_LOGDOMAIN, "Empty message, not sending");
        AQH_Message_free(msg);
      }
      else {
        AQH_Message_List_Add(msg, xo->msgOutList);
        if (xo->msgWriter && AQH_Message_List_GetCount(xo->msgOutList)==1) {
          DBG_INFO(AQH_LOGDOMAIN, "Enabling msgWriter, sending message");
          AQH_MsgWriter_SendMsg(xo->msgWriter, AQH_Message_GetMsgPointer(msg), AQH_Message_GetUsedSize(msg));
          AQH_Object_Enable(xo->msgWriter);
        }
      }
    }
  }
}



AQH_MESSAGE_LIST *AQH_Endpoint_GetMsgInList(const AQH_OBJECT *o)
{
  if (o) {
    AQH_ENDPOINT *xo;

    xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQH_ENDPOINT, o);
    if (xo)
      return xo->msgInList;
  }
  return NULL;
}



AQH_MESSAGE *AQH_Endpoint_GetNextMsgIn(AQH_OBJECT *o)
{
  if (o) {
    AQH_ENDPOINT *xo;

    xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQH_ENDPOINT, o);
    if (xo) {
      AQH_MESSAGE *msg;

      msg=AQH_Message_List_First(xo->msgInList);
      if (msg) {
        AQH_Message_List_Del(msg);
        return msg;
      }
    }
  }
  return NULL;
}



void AQH_Endpoint_AddMsgIn(AQH_OBJECT *o, AQH_MESSAGE *msg)
{
  if (o && msg) {
    AQH_ENDPOINT *xo;

    xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQH_ENDPOINT, o);
    if (xo) {
      AQH_Message_List_Add(msg, xo->msgInList);
      DBG_DEBUG(AQH_LOGDOMAIN, "now %d msgs in list", AQH_Message_List_GetCount(xo->msgInList));
    }
  }
}



uint32_t AQH_Endpoint_GetLastMessageId(const AQH_OBJECT *o)
{
  if (o) {
    AQH_ENDPOINT *xo;

    xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQH_ENDPOINT, o);
    if (xo)
      return xo->lastMsgId;
  }
  return 0;
}



uint32_t AQH_Endpoint_GetNextMessageId(AQH_OBJECT *o)
{
  if (o) {
    AQH_ENDPOINT *xo;

    xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQH_ENDPOINT, o);
    if (xo)
      return ++(xo->lastMsgId);
  }
  return 0;
}



int _handleSignal(AQH_OBJECT *o, uint32_t slotId, GWEN_UNUSED AQH_OBJECT *senderObject, int param1, void *param2)
{
  switch(slotId) {
  case AQH_ENDPOINT_SLOT_MSG_RECVD: return _handleMsgRecvd(o, param1, param2);
  case AQH_ENDPOINT_SLOT_MSG_SENT:  return _handleMsgSent(o);
  case AQH_ENDPOINT_SLOT_CLOSED:    return _handleClosed(o);
  default:
    break;
  }

  return 0; /* not handled */
}



int _handleMsgRecvd(AQH_OBJECT *o, int msgLen, const uint8_t *msgPtr)
{
  AQH_MESSAGE *msg;

  DBG_DEBUG(AQH_LOGDOMAIN, "Msg received:");
  /*GWEN_Text_LogString((const char*) msgPtr, msgLen, AQH_LOGDOMAIN, GWEN_LoggerLevel_Error);*/
  msg=AQH_NodeMessage_fromBuffer(msgPtr, msgLen);
  AQH_Endpoint_AddMsgIn(o, msg);

  return 1;
}



int _handleMsgSent(AQH_OBJECT *o)
{
  DBG_DEBUG(AQH_LOGDOMAIN, "Msg sent");
  if (o) {
    AQH_ENDPOINT *xo;

    xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQH_ENDPOINT, o);
    if (xo) {
      AQH_MESSAGE *msg;

      DBG_DEBUG(AQH_LOGDOMAIN, "Messages in outlist: %d", AQH_Message_List_GetCount(xo->msgOutList));
      msg=AQH_Message_List_First(xo->msgOutList);
      if (msg) {
        /* remove sent message from list */
        AQH_Message_List_Del(msg);
        AQH_Message_free(msg);

        /* get next message in list */
        msg=AQH_Message_List_First(xo->msgOutList);
        if (msg) {
          DBG_DEBUG(AQH_LOGDOMAIN, "Sending next message");
          AQH_MsgWriter_SendMsg(xo->msgWriter, AQH_Message_GetMsgPointer(msg), AQH_Message_GetUsedSize(msg));
        }
        else {
          DBG_INFO(AQH_LOGDOMAIN, "Last message sent, disabling writer");
          AQH_Object_Disable(xo->msgWriter);
        }
      }
    }
  }

  return 1;
}



int _handleClosed(AQH_OBJECT *o)
{
  AQH_ENDPOINT *xo;

  DBG_INFO(AQH_LOGDOMAIN, "Connection closed.");
  xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQH_ENDPOINT, o);
  if (xo) {
    AQH_Object_Disable(xo->msgWriter);
    AQH_Object_Disable(xo->msgReader);
    if (0==AQH_Object_EmitSignal(o, AQH_ENDPOINT_SIGNAL_CLOSED, 0, NULL)) {
      DBG_ERROR(AQH_LOGDOMAIN, "Signal CLOSED not handled");
    }
    return 1;
  }
  return 0;
}



