/****************************************************************************
 * 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/data/msg_data_connect.h>
#include <aqhome/ipc/data/ipc_data.h>
#include <aqhome/ipc/msg_ipc_tag16.h>

#include <gwenhywfar/msg.h>
#include <gwenhywfar/buffer.h>

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



#define AQH_MSGDATA_CONNECT_MINSIZE GWEN_MSGIPC_OFFS_PAYLOAD




GWEN_MSG *AQH_ConnectDataIpcMsg_new(uint16_t code, const char *clientId, const char *userId, const char *password, uint32_t flags)
{
  GWEN_MSG *msg;
  GWEN_BUFFER *buf;

  buf=GWEN_Buffer_new(0, 256, 0, 1);
  if (clientId && *clientId)
    GWEN_Tag16_WriteStringTagToBuffer(AQH_MSGDATA_CONNECT_TAGS_CLIENTID, clientId, buf);
  if (userId && *userId)
    GWEN_Tag16_WriteStringTagToBuffer(AQH_MSGDATA_CONNECT_TAGS_USERID, userId, buf);
  if (password && *password)
    GWEN_Tag16_WriteStringTagToBuffer(AQH_MSGDATA_CONNECT_TAGS_PASSWORD, password, buf);
  GWEN_Tag16_WriteUint32TagToBuffer(AQH_MSGDATA_CONNECT_TAGS_FLAGS, flags, buf);

  msg=AQH_Tag16IpcMsg_new(AQH_IPC_PROTOCOL_DATA_ID, AQH_IPC_PROTOCOL_DATA_VERSION, code,
                          GWEN_Buffer_GetUsedBytes(buf), (const uint8_t*) GWEN_Buffer_GetStart(buf));
  GWEN_Buffer_free(buf);
  return msg;
}



void AQH_ConnectDataIpcMsg_Parse(GWEN_MSG *msg, int doCopy)
{
  AQH_Tag16IpcMsg_ExtendAndParse(msg, doCopy);
}



void AQH_ConnectDataIpcMsg_DumpToBuffer(const GWEN_MSG *msg, GWEN_BUFFER *dbuf, const char *sText)
{
  if (GWEN_Msg_GetBytesInBuffer(msg)>=AQH_MSGDATA_CONNECT_MINSIZE) {
    char *clientId;
    char *userId;
    uint32_t flags;

    clientId=AQH_Tag16IpcMsg_GetTagDataAsNewString(msg, AQH_MSGDATA_CONNECT_TAGS_CLIENTID, NULL);
    userId=AQH_Tag16IpcMsg_GetTagDataAsNewString(msg, AQH_MSGDATA_CONNECT_TAGS_USERID, NULL);
    flags=AQH_Tag16IpcMsg_GetTagDataAsUint32(msg, AQH_MSGDATA_CONNECT_TAGS_FLAGS, 0);

    GWEN_Buffer_AppendArgs(dbuf,
                           "CONNECT (code=%d, proto=%d, proto version=%d, clientId=%s, userId=%s, flags=%08x)\n",
                           GWEN_IpcMsg_GetCode(msg),
                           GWEN_IpcMsg_GetProtoId(msg),
                           GWEN_IpcMsg_GetProtoVersion(msg),
                           clientId?clientId:"<empty>",
			   userId?userId:"<empty>",
			   flags);
    free(userId);
    free(clientId);
  }
}







