/****************************************************************************
 * 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 "./r_forward.h"
#include "./server_p.h"
#include "aqhome/ipc2/endpoint.h"
#include "aqhome/msg/ipc/m_ipc.h"
#include "aqhome/msg/ipc/nodes/m_ipcn.h"
#include "aqhome/msg/ipc/nodes/m_ipcn_forward.h"
#include "aqhome/msg/ipc/m_ipc_connect.h"
#include "aqhome/msg/ipc/m_ipc_result.h"
#include "aqhome/msg/ipc/m_ipc_tag16.h"
#include <aqhome/msg/node/m_node.h>

#include <gwenhywfar/debug.h>



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

void AQH_NodeServer_HandleForward(AQH_OBJECT *o, AQH_OBJECT *ep, const AQH_MESSAGE *msg, const GWEN_TAG16_LIST *tagList)
{
  AQH_NODE_SERVER *xo;

  xo=AQH_NodeServer_GetServerData(o);
  if (xo) {
    AQH_MESSAGE *outMsg;
    int resultCode=AQH_MSGDATA_RESULT_SUCCESS;
    const GWEN_TAG16 *tag;
    const uint8_t *ptr;
    uint32_t len;

    tag=tagList?GWEN_Tag16_List_FindFirstByTagType(tagList, AQH_MSGNODE_FORWARD_TAGS_MSG):NULL;
    ptr=tag?GWEN_Tag16_GetTagData(tag):NULL;
    len=tag?GWEN_Tag16_GetTagLength(tag):0;

    if (ptr && len) {
      if (xo->ttyEndpoint) {
        AQH_MESSAGE *nodeMsg;

        nodeMsg=AQH_Message_new();
        AQH_Message_SetData(nodeMsg, ptr, len);
        AQH_Message_SetUsedSize(nodeMsg, len);
        AQH_Endpoint_AddMsgOut(xo->ttyEndpoint, nodeMsg);
        AQH_NodeServer_WriteTtyMsgToLogFile(o, nodeMsg, "sending");
        DBG_ERROR(NULL, "Forwarding node message %d to node", AQH_NodeMessage_GetMsgType(nodeMsg));
      }
      else {
        DBG_ERROR(NULL, "TTY endpoint currently not connected");
        resultCode=AQH_MSGDATA_RESULT_ERROR_TRYAGAIN;
      }
    }
    else {
      DBG_ERROR(NULL, "Empty message to forward");
      resultCode=AQH_MSGDATA_RESULT_ERROR_BADDATA;
    }

    outMsg=AQH_IpcMessageResult_new(AQH_IPC_PROTOCOL_NODES_ID,
                                    AQH_IPC_PROTOCOL_NODES_VERSION,
                                    AQH_MSGTYPE_IPC_NODES_RESULT,
                                    AQH_Endpoint_GetNextMessageId(ep),
                                    AQH_IpcMessage_GetMsgId(msg),
                                    resultCode, NULL);
    AQH_Endpoint_AddMsgOut(ep, outMsg);
  }
}



