/****************************************************************************
 * 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 "aqhome/ipc/endpoint_node_ipc.h"
#include "aqhome/msg/endpoint_node.h"
#include "aqhome/msg/msg_node.h"
#include "aqhome/msg/msg_value2.h"
#include "aqhome/ipc/msg_ipc_forward.h"
#include "aqhome/ipc/msg_ipc_value.h"

#include <gwenhywfar/list.h>
#include <gwenhywfar/debug.h>
#include <gwenhywfar/gwentime.h>
#include <gwenhywfar/endpoint_ipc.h>


#define AQH_MSG_ENDPOINT_NODEIPC_NAME            "nodeipc"



static void _processOutMessage(GWEN_MSG_ENDPOINT *ep, GWEN_MSG *m);
static void _processValue2Message(GWEN_MSG_ENDPOINT *ep, GWEN_MSG *nodeMsg);
static void _forwardAnyMessage(GWEN_MSG_ENDPOINT *ep, GWEN_MSG *nodeMsg);





GWEN_MSG_ENDPOINT *AQH_IpcNodeEndpoint_new(const char *name, int groupId)
{
  GWEN_MSG_ENDPOINT *ep;

  ep=GWEN_IpcEndpoint_new(name?name:AQH_MSG_ENDPOINT_NODEIPC_NAME, groupId);
  AQH_NodeEndpoint_Extend(ep);
  GWEN_MsgEndpoint_SetProcessOutMsgFn(ep, _processOutMessage);

  AQH_NodeEndpoint_SetAcceptedMsgGroups(ep, AQH_MSG_TYPEGROUP_ALL);

  return ep;
}



void _processOutMessage(GWEN_MSG_ENDPOINT *ep, GWEN_MSG *nodeMsg)
{
  switch(AQH_NodeMsg_GetMsgType(nodeMsg)) {
  case AQH_MSG_TYPE_VALUE2:
    _processValue2Message(ep, nodeMsg);
    break;
  default:
    _forwardAnyMessage(ep, nodeMsg);
    break;
  }

  GWEN_Msg_free(nodeMsg);
}



void _processValue2Message(GWEN_MSG_ENDPOINT *ep, GWEN_MSG *nodeMsg)
{
  GWEN_MSG *ipcMsg;

  ipcMsg=AQH_ValueIpcMsg_new(AQH_MSGTYPE_IPC_VALUE,
                             AQH_Value2Msg_GetUid(nodeMsg),
                             AQH_Value2Msg_GetValueId(nodeMsg),
                             AQH_Value2Msg_GetValueType(nodeMsg),
                             AQH_Value2Msg_GetValueNom(nodeMsg),
                             AQH_Value2Msg_GetValueDenom(nodeMsg));
  GWEN_MsgEndpoint_AddSendMessage(ep, ipcMsg);
}



void _forwardAnyMessage(GWEN_MSG_ENDPOINT *ep, GWEN_MSG *nodeMsg)
{
  GWEN_MSG *ipcMsg;

  ipcMsg=AQH_ForwardIpcMsg_new(AQH_MSGTYPE_IPC_FORWARD, GWEN_Msg_GetConstBuffer(nodeMsg), GWEN_Msg_GetBytesInBuffer(nodeMsg));
  GWEN_MsgEndpoint_AddSendMessage(ep, ipcMsg);
}






