#ifndef MISSION_DEVICES_PLOCMPSOCHANDLER_H_
#define MISSION_DEVICES_PLOCMPSOCHANDLER_H_

#include <fsfw/devicehandlers/DeviceHandlerBase.h>
#include <mission/devices/devicedefinitions/PlocMPSoCDefinitions.h>

#include <cstring>

/**
 * @brief	This is the device handler for the MPSoC which is programmed by the ILH of the
 *          university of stuttgart.
 *
 * @details
 * The PLOC uses the space packet protocol for communication. To each command the PLOC
 * answers with at least one acknowledgment and one execution report.
 * Flight manual:
 * https://egit.irs.uni-stuttgart.de/redmine/projects/eive-flight-manual/wiki/PLOC_Commands
 * ILH ICD: https://eive-cloud.irs.uni-stuttgart.de/index.php/apps/files/?dir=/EIVE_IRS/
 *          Arbeitsdaten/08_Used%20Components/PLOC&fileid=940960
 * @author	J. Meier
 */
class PlocMPSoCHandler : public DeviceHandlerBase {
 public:
  PlocMPSoCHandler(object_id_t objectId, object_id_t comIF, CookieIF* comCookie);
  virtual ~PlocMPSoCHandler();

  /**
   * @brief   Sets mode to MODE_NORMAL. Can be used for debugging.
   */
  void setModeNormal();

 protected:
  void doStartUp() override;
  void doShutDown() override;
  ReturnValue_t buildNormalDeviceCommand(DeviceCommandId_t* id) override;
  ReturnValue_t buildTransitionDeviceCommand(DeviceCommandId_t* id) override;
  void fillCommandAndReplyMap() override;
  ReturnValue_t buildCommandFromCommand(DeviceCommandId_t deviceCommand, const uint8_t* commandData,
                                        size_t commandDataLen) override;
  ReturnValue_t scanForReply(const uint8_t* start, size_t remainingSize, DeviceCommandId_t* foundId,
                             size_t* foundLen) override;
  ReturnValue_t interpretDeviceReply(DeviceCommandId_t id, const uint8_t* packet) override;
  void setNormalDatapoolEntriesInvalid() override;
  uint32_t getTransitionDelayMs(Mode_t modeFrom, Mode_t modeTo) override;
  ReturnValue_t initializeLocalDataPool(localpool::DataPool& localDataPoolMap,
                                        LocalDataPoolManager& poolManager) override;
  ReturnValue_t enableReplyInReplyMap(DeviceCommandMap::iterator command,
                                      uint8_t expectedReplies = 1, bool useAlternateId = false,
                                      DeviceCommandId_t alternateReplyID = 0) override;
  size_t getNextReplyLength(DeviceCommandId_t deviceCommand) override;

 private:
  static const uint8_t INTERFACE_ID = CLASS_ID::PLOC_MPSOC_HANDLER;

  //! Space Packet received from PLOC has invalid CRC
  static const ReturnValue_t CRC_FAILURE = MAKE_RETURN_CODE(0xA0);
  //! Received ACK failure reply from PLOC
  static const ReturnValue_t RECEIVED_ACK_FAILURE = MAKE_RETURN_CODE(0xA1);
  //! Received execution failure reply from PLOC
  static const ReturnValue_t RECEIVED_EXE_FAILURE = MAKE_RETURN_CODE(0xA2);
  //! Received space packet with invalid APID from PLOC
  static const ReturnValue_t INVALID_APID = MAKE_RETURN_CODE(0xA3);

  static const uint8_t SUBSYSTEM_ID = SUBSYSTEM_ID::PLOC_MPSOC_HANDLER;

  //! PLOC crc failure in telemetry packet
  static const Event MEMORY_READ_RPT_CRC_FAILURE = MAKE_EVENT(1, severity::LOW);
  //! PLOC receive acknowledgment failure report
  static const Event ACK_FAILURE = MAKE_EVENT(2, severity::LOW);
  //! PLOC receive execution failure report
  static const Event EXE_FAILURE = MAKE_EVENT(3, severity::LOW);
  //! PLOC reply has invalid crc
  static const Event CRC_FAILURE_EVENT = MAKE_EVENT(4, severity::LOW);

  static const uint16_t APID_MASK = 0x7FF;
  static const uint16_t PACKET_SEQUENCE_COUNT_MASK = 0x3FFF;

  uint8_t commandBuffer[PLOC_MPSOC::MAX_COMMAND_SIZE];

  /**
   * @brief   This object is incremented each time a packet is sent or received. By checking the
   *          packet sequence count of a received packet, no packets can be lost without noticing
   *          it. Only the least significant 14 bits represent the packet sequence count in a
   *          space packet. Thus the maximum value amounts to 16383 (0x3FFF).
   * @note    Normally this should never happen because the PLOC replies are always sent in a
   *          fixed order. However, the PLOC software checks this value and will return an ACK
   *          failure report in case the sequence count is not incremented with each transferred
   *          space packet.
   */
  uint16_t packetSequenceCount = 0x3FFF;

  /**
   * This variable is used to store the id of the next reply to receive. This is necessary
   * because the PLOC sends as reply to each command at least one acknowledgment and execution
   * report.
   */
  DeviceCommandId_t nextReplyId = PLOC_MPSOC::NONE;

  /**
   * @brief   This function fills the commandBuffer to initiate the write memory command.
   *
   * @param commandData   Pointer to action command data.
   * @param commanDataLen Size of command data in bytes.
   *
   * @return RETURN_OK if successful, else RETURN_FAILURE.
   */
  ReturnValue_t prepareTcMemWriteCommand(const uint8_t* commandData, size_t commandDataLen);

  /**
   * @brief   This function fills the commandBuffer to initiate the write reads command.
   *
   * @param commandData   Pointer to action command data.
   * @param commanDataLen Size of command data in bytes.
   *
   * @return RETURN_OK if successful, else RETURN_FAILURE.
   */
  ReturnValue_t prepareTcMemReadCommand(const uint8_t* commandData, size_t commandDataLen);

  /**
   * @brief   This function checks the crc of the received PLOC reply.
   *
   * @param start Pointer to the first byte of the reply.
   * @param foundLen  Pointer to the length of the whole packet.
   *
   * @return  RETURN_OK if CRC is ok, otherwise CRC_FAILURE.
   */
  ReturnValue_t verifyPacket(const uint8_t* start, size_t foundLen);

  /**
   * @brief   This function handles the acknowledgment report.
   *
   * @param data  Pointer to the data holding the acknowledgment report.
   *
   * @return  RETURN_OK if successful, otherwise an error code.
   */
  ReturnValue_t handleAckReport(const uint8_t* data);

  /**
   * @brief   This function handles the data of a execution report.
   *
   * @param data  Pointer to the received data packet.
   *
   * @return  RETURN_OK if successful, otherwise an error code.
   */
  ReturnValue_t handleExecutionReport(const uint8_t* data);

  /**
   * @brief   This function handles the memory read report.
   *
   * @param data  Pointer to the data buffer holding the memory read report.
   *
   * @return  RETURN_OK if successful, otherwise an error code.
   */
  ReturnValue_t handleMemoryReadReport(const uint8_t* data);

  /**
   * @brief   Depending on the current active command, this function sets the reply id of the
   *          next reply after a successful acknowledgment report has been received. This is
   *          required by the function getNextReplyLength() to identify the length of the next
   *          reply to read.
   */
  void setNextReplyId();

  /**
   * @brief   This function handles action message replies in case the telemetry has been
   *          requested by another object.
   *
   * @param data  Pointer to the telemetry data.
   * @param dataSize  Size of telemetry in bytes.
   * @param replyId   Id of the reply. This will be added to the ActionMessage.
   */
  void handleDeviceTM(const uint8_t* data, size_t dataSize, DeviceCommandId_t replyId);

  /**
   * @brief   In case an acknowledgment failure reply has been received this function disables
   *          all previously enabled commands and resets the exepected replies variable of an
   *          active command.
   */
  void disableAllReplies();

  /**
   * @brief   This function sends a failure report if the active action was commanded by an other
   *          object.
   *
   * @param replyId   The id of the reply which signals a failure.
   * @param status    A status byte which gives information about the failure type.
   */
  void sendFailureReport(DeviceCommandId_t replyId, ReturnValue_t status);

  /**
   * @brief   This function disables the execution report reply. Within this function also the
   *          the variable expectedReplies of an active command will be set to 0.
   */
  void disableExeReportReply();

  /**
   * @brief   This function checks and increments the packet sequence count of a received space
   *          packet.
   *
   * @param data  Pointer to a space packet.
   *
   * @return RETURN_OK if successful
   *
   * @details There should be never a case in which a wrong packet sequence count is received
   *          because the communication scheme between PLOC and OBC always follows a strict
   *          procedure. Thus this function mainly serves for debugging purposes to detected an
   *          invalid handling of the packet sequence count.
   */
  ReturnValue_t checkPacketSequenceCount(const uint8_t* data);
};

#endif /* MISSION_DEVICES_PLOCMPSOCHANDLER_H_ */