/****************************************************************************
 * 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 "aqhome/msg/ipc/m_ipc_result.h"
#include "aqhome/msg/ipc/m_ipc_tag16.h"
#include "aqhome/msg/ipc/m_ipc.h"

#include <gwenhywfar/text.h>
#include <gwenhywfar/tag16.h>
#include <gwenhywfar/buffer.h>



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



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

AQH_MESSAGE *AQH_IpcMessageResult_new(uint8_t protoId, uint8_t protoVer, uint16_t code,
                                      uint32_t msgId, uint32_t refMsgId,
                                      int result, const char *text)
{
  AQH_MESSAGE *msg;
  GWEN_BUFFER *buf;

  buf=GWEN_Buffer_new(0, 256, 0, 1);
  GWEN_Tag16_WriteUint32TagToBuffer(AQH_MSGDATA_RESULT_TAGS_RESULT, result, buf);
  if (text && *text)
    GWEN_Tag16_WriteStringTagToBuffer(AQH_MSGDATA_RESULT_TAGS_TEXT, text, buf);

  msg=AQH_IpcMessage_new(protoId, protoVer, code, msgId, refMsgId,
                         GWEN_Buffer_GetUsedBytes(buf), (const uint8_t*) GWEN_Buffer_GetStart(buf));
  GWEN_Buffer_free(buf);
  return msg;
}



uint32_t AQH_IpcMessageResult_GetResult(const GWEN_TAG16_LIST *tagList)
{
  return tagList?AQH_Tag16_GetTagDataAsUint32(tagList, AQH_MSGDATA_RESULT_TAGS_RESULT, 0):0;
}



char *AQH_IpcMessageResult_GetText(const GWEN_TAG16_LIST *tagList)
{
  return tagList?AQH_Tag16_GetTagDataAsNewString(tagList, AQH_MSGDATA_RESULT_TAGS_TEXT, NULL):0;
}



void AQH_IpcMessageResult_DumpToBuffer(const AQH_MESSAGE *msg, const GWEN_TAG16_LIST *tagList, GWEN_BUFFER *dbuf, const char *sText)
{
  int result=0;
  char *text=NULL;

  if (tagList) {
    result=AQH_Tag16_GetTagDataAsUint32(tagList, AQH_MSGDATA_RESULT_TAGS_RESULT, 0);
    text=AQH_Tag16_GetTagDataAsNewString(tagList, AQH_MSGDATA_RESULT_TAGS_TEXT, NULL);
  }

  GWEN_Buffer_AppendArgs(dbuf,
                         "RESULT %s (code=%d, proto=%d, proto version=%d, result=%d, text=\"%s\")\n",
                         sText?sText:"",
                         AQH_IpcMessage_GetCode(msg),
                         AQH_IpcMessage_GetProtoId(msg),
                         AQH_IpcMessage_GetProtoVersion(msg),
                         result,
                         text?text:"");
  free(text);
}





