/****************************************************************************
 * 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_getnodes.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_setaccmsggrps.h"
#include "aqhome/msg/ipc/nodes/m_ipcn_getdevices_rsp.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 <gwenhywfar/debug.h>



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

void AQH_NodeServer_HandleGetNodes(AQH_OBJECT *o, AQH_OBJECT *ep, const AQH_MESSAGE *msg)
{
  AQH_NODE_SERVER *xo;

  xo=AQH_NodeServer_GetServerData(o);
  if (xo) {
    AQH_NODE_INFO_LIST *nodeInfoList;

    nodeInfoList=AQH_NodeDb_GetAllNodeInfos(xo->nodeDb);
    if (nodeInfoList && AQH_NodeInfo_List_GetCount(nodeInfoList)) {
      const AQH_NODE_INFO *ni;
  
      ni=AQH_NodeInfo_List_First(nodeInfoList);
      while(ni) {
        const AQH_NODE_INFO *niNext;
        AQH_MESSAGE *outMsg;
  
        niNext=AQH_NodeInfo_List_Next(ni);
        DBG_INFO(AQH_LOGDOMAIN, "Sending response for node %02x (%08x)", AQH_NodeInfo_GetBusAddress(ni), AQH_NodeInfo_GetUid(ni));
        outMsg=AQH_IpcnMessageGetDevicesRsp_new(AQH_MSGTYPE_IPC_NODES_GETDEVICES_RSP,
                                                AQH_Endpoint_GetNextMessageId(ep), AQH_IpcMessage_GetMsgId(msg),
                                                niNext?0:AQH_MSGNODE_GETDEVICES_RSP_FLAGS_LASTMSG, ni);
        AQH_Endpoint_AddMsgOut(ep, outMsg);
        DBG_DEBUG(NULL, "Messages in clients out queue: %d", AQH_Message_List_GetCount(AQH_Endpoint_GetMsgOutList(ep)));
        ni=niNext;
      }
    }
    else {
      AQH_MESSAGE *outMsg;
  
      DBG_INFO(AQH_LOGDOMAIN, "No nodes");
      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),
                                      AQH_MSGDATA_RESULT_ERROR_NODATA, NULL);
      AQH_Endpoint_AddMsgOut(ep, outMsg);
    }
  }
}



