/*
  message.h

  Copyright (c) 2021 Kevin Matz (kevin.matz@gmail.com)

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  SOFTWARE.
*/
#pragma once

#include <cstdint>
#include <memory>
#include <vector>

#include "rdm.h"
#include "uid.h"

namespace RDM {

struct Message;

using MsgPtr = std::shared_ptr<Message>; //!< valid RDM Message

/**
 * @brief The Message struct
 */
struct Message
{
  Message();
  Message(const Message &obj);
  Message(const std::vector<uint8_t> &data);

  void read(const std::vector<uint8_t> &data);
  void write(std::vector<uint8_t> &data) const;
  void nak(uint16_t reason);

  UID source;             //!< source UID
  UID destination;        //!< destination UID
  uint8_t transaction;    //!< transaction number
  union {
    uint8_t portID;       //!< destination port
    uint8_t responseType; //!< type of response
  };
  uint8_t messageCount;   //!< message count number
  uint16_t subDevice;     //!< destination subdevice
  uint8_t commandClass;   //!< message command class
  PID parameterId;        //!< PID

  union {
    uint8_t failure_mode;
    struct {
      bool short_message   : 1; //!< undersized buffer
      bool length_mismatch : 1; //!< message longer than adervertised
      bool checksum_fail   : 1; //!< message did not match checksum
      bool incorrect_sc    : 1; //!< invalid StartCode
      bool incorrect_sub_sc: 1; //!< invalid sub-StartCode
      bool do_not_send     : 1; //!< message does not require transmission
    };
  };

  const std::vector<uint8_t>* data() const;
  uint8_t length() const;
  uint16_t checksum() const;
  bool requiredLength(const size_t length, MsgPtr response) const;
  /**
   * @brief appendData
   * @param val
   */
  template<typename T>
  void appendData(const T & val)
  {
    Message::writeType<T>(data_, val);
  }
  /**
   * @brief readType
   * @param vect
   * @param start
   * @return
   */
  template<typename T>
  static T readType(const std::vector<uint8_t>& vect, size_t start)
  {
    if (vect.size() < sizeof(T))
      return 0;
    T ret = 0;
    auto data = reinterpret_cast<uint8_t*>(&ret);
    for (int i = sizeof(T);  --i >= 0; )
        data[i] = vect[start + i];
    return ret;
  }
  /**
   * @brief writeType
   * @param data
   * @param val
   */
  template<typename T>
  static void writeType(std::vector<uint8_t>& data, T val)
  {
    if (val == 0)
      {
        for (int i = sizeof(T);  --i >= 0; )
          data.push_back(0);
        return;
      }
    auto raw = reinterpret_cast<uint8_t*>(val);
    for (int i = sizeof(T);  --i >= 0; )
      data.push_back(raw[i]);
  }

private:
  std::vector<uint8_t> data_;
  void writeDiscBranch(std::vector<uint8_t> &data) const;

  template<typename T>
  uint16_t addSum_(uint16_t sum, T val) const
  {
    uint16_t carry;
    auto raw = reinterpret_cast<uint8_t*>(val);
    for (int i = sizeof(T);  --i >= 0; )
      {
        uint8_t num = raw[i];
        while (num != 0)
          {
            carry = sum & num;
            sum = sum ^ num;
            num = carry << 1;
          }
      }
    return sum;
  }
}; // struct Message


} // namespace RDM

