/**
 * @file   AXFComm.cpp
 */

#include "AXFCommInternal.hpp"

#include <stdio.h>
#include <string.h>

/*
 * AXFComm 共有メモリ・フォーマット
 *  +-----------------+---------------------------------+--------------+---------------+-----------------------+
 *  | totalSize(4) | ObjectNameString(NULL stop) | eventID(4) | dataSize(4) | data ...           |
 *  +-----------------+---------------------------------+--------------+---------------+-----------------------+
 *
 *  | --->           totalSize                                                              <--- |
 *                                                                          | ---> dataSize <--- |
 */

#define AXFCOMM_INDEX_TOTAL_SIZE          (0)
#define AXFCOMM_INDDEX_OBJECT_NAME_STRING (AXFCOMM_INDEX_TOTAL_SIZE + sizeof(INT32_t))
#define AXFCOMM_INDEX_EVENTID             (AXFCOMM_INDDEX_OBJECT_NAME_STRING + strlen(&buf[AXFCOMM_INDDEX_OBJECT_NAME_STRING]) + 1)
#define AXFCOMM_INDEX_DATA_SIZE           (AXFCOMM_INDEX_EVENTID + sizeof(AXFEvent_t))
#define AXFCOMM_INDEX_DATA                (AXFCOMM_INDEX_DATA_SIZE + sizeof(INT32_t))

char* AXFCommInternal::getObjectNameStringPtr(char* buf) {
  return &buf[AXFCOMM_INDDEX_OBJECT_NAME_STRING];
}

AXFEvent_t AXFCommInternal::getEventId(char* buf) {
  return *(AXFEvent_t*) (&buf[AXFCOMM_INDEX_EVENTID]);
}

INT32_t AXFCommInternal::getDataSize(char* buf) {
  return *(int *) (&buf[AXFCOMM_INDEX_DATA_SIZE]);
}

char* AXFCommInternal::getDataPtr(char* buf) {
  return (char *) (&buf[AXFCOMM_INDEX_DATA]);
}

INT32_t AXFCommInternal::setPacket(char* buf, INT32_t bufSize, const char* name,
                                   AXFEvent_t eventId, void* data,
                                   INT32_t size) {
  INT32_t totalSize = sizeof(INT32_t) + strlen(name) + 1
      + sizeof(AXFEvent_t) + sizeof(INT32_t) + size;

  if (totalSize > bufSize) {
    return -1;
  }

  strcpy(&buf[AXFCOMM_INDDEX_OBJECT_NAME_STRING],name);
  *(AXFEvent_t*) (&buf[AXFCOMM_INDEX_EVENTID]) = eventId;
  *(INT32_t*) (&buf[AXFCOMM_INDEX_DATA_SIZE]) = size;
  memcpy(&buf[AXFCOMM_INDEX_DATA], data, size);
  *(INT32_t*) (&buf[AXFCOMM_INDEX_TOTAL_SIZE]) = totalSize;
  return totalSize;
}

AXFCommInternal::commStatus AXFCommInternal::init(AXComm_t type) {
	return AXCCommFreeRTOS::init(type);
}

int AXFCommInternal::readSync(char *buf, int size) {
	return AXCCommFreeRTOS::readSync(buf, size);
}

int AXFCommInternal::writeSync(char *buf, int size) {
	return AXCCommFreeRTOS::writeSync(buf, size);
}
