/*
  receiver.cpp

  Copyright (c) 2020 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.
*/

#include "acn/pdu.h"
#include "receiver.h"
#include "config.h"

namespace SACN {

/**
 * @brief Receiver::Receiver
 * @param cid
 *
 * Constructor.  Register RLP vector callbacks.
 */
Receiver::Receiver(UUID::uuid cid)
  : Component(cid)
{
  fctn_ = "OpenLCP sACN Receiver";

  RlpRegisterVector(VECTOR_ROOT_E131_DATA, std::bind(&Receiver::dataReceiver,
                                                  this, std::placeholders::_1));
  RlpRegisterVector(VECTOR_ROOT_E131_EXTENDED, std::bind(&Receiver::extendedReceiver,
                                                  this, std::placeholders::_1));
}


/**
 * @brief Receiver::~Receiver
 */
Receiver::~Receiver()
{
  for (auto& [_, universe] : universes_)
    delete universe;
}


/**
 * @brief Receiver::subscribe
 * @param num
 */
void Receiver::subscribe(const uint16_t num) {
  if (universes_.count(num))
    return;
  universes_.emplace(num, new MergeProxyUniverse());
}


/**
 * @brief Receiver::unsubscribe
 * @param num
 */
void Receiver::unsubscribe(const uint16_t num) {
  if (universes_.count(num))
    {
      delete universes_.at(num);
      universes_.erase(num);
    }
}


/**
 * @brief Receiver::universe
 * @param num
 * @return
 */
Universe * Receiver::universe(const uint16_t num) {
  if (!universes_.count(num))
    return nullptr;
  return universes_.at(num);
}


/**
 * @brief Receiver::discoveryStart
 */
void Receiver::discoveryStart() {
  subscribe(SACN::E131_DISCOVERY_UNIVERSE);
}


/**
 * @brief Receiver::discoveryStop
 */
void Receiver::discoveryStop() {
  unsubscribe(SACN::E131_DISCOVERY_UNIVERSE);
}


/**
 * @brief Receiver::onDiscovered
 * @param cb something that wants to know about available universes.
 */
void Receiver::onDiscovered(const EXTENDED::DISCOVERY::Watcher cb) {
  discoveryCallbacks_.push_back(cb);
}


/**
 * @brief Receiver::dataReceiver - dispatcher of RLP DATA PDU
 * @param root a shared pointer to the PDU
 *
 * Receive VECTOR_ROOT_E131_DATA vector'd packets.
 */
void Receiver::dataReceiver(ACN::PDU::Message<ACN::RLP::Pdu> root)
{
  root->createDataBlock<DATA::Pdu>();
  // a PDU::Block is guaranteed to have been instantiated, but if the input
  // stream failed, it will not list any PDU.  OK to loop without checking
  // the state of the stream.
  auto block = static_cast<ACN::PDU::Block<DATA::Pdu>*>(root->data());
  for(auto const &frame : *block->pdu)
    {
      /// 6.2.1 E1.31 Data Packet: Vector
      /// Sources sending an E1.31 Data Packet shall set the E1.31 Layer's Vector
      /// to VECTOR_E131_DATA_PACKET. This value indicates that the E1.31 framing
      /// layer is wrapping a DMP PDU.
      switch(frame->vector()) {
        case VECTOR_E131_DATA_PACKET:
          dataFrameHandler(frame);
          break;
        default:
          break;
        }
    }
}


/**
 * @brief Receiver::extendedReceiver - dispatcher of RLP EXTENDED PDU
 * @param root a shared pointer to the PDU
 *
 * Receive VECTOR_ROOT_E131_EXTENDED vector'd packets.
 */
void Receiver::extendedReceiver(ACN::PDU::Message<ACN::RLP::Pdu> root)
{
  root->createDataBlock<EXTENDED::Pdu>();
  // a PDU::Block is guaranteed to have been instantiated, but if the input
  // stream failed, it will not list any PDU.  OK to loop without checking
  // the state of the stream.
  auto block = static_cast<ACN::PDU::Block<EXTENDED::Pdu>*>(root->data());
  for(auto const &frame : *block->pdu)
    {
      switch(frame->vector()) {
        /// 6.3 E1.31 Synchronization Packet Framing Layer
        case VECTOR_E131_EXTENDED_SYNCHRONIZATION:
          syncFrameHandler(frame);
          break;
         /// 6.4 E1.31 Universe Discovery Packet Framing Layer
        case VECTOR_E131_EXTENDED_DISCOVERY:
          discoveryFrameHandler(frame);
          break;
        default:
          break;
        }
    }
}


/**
 * @brief Receiver::dataFrameHandler
 * @param frame
 *
 * Receive `VECTOR_ROOT_E131_DATA -> VECTOR_E131_DATA_PACKET` vector'd packets.
 *
 * Merging will be based on frame header.  PDU data will be read as a block of
 * DMP PDUs and passed to the universe.
 *
 */
void Receiver::dataFrameHandler(ACN::PDU::Message<DATA::Pdu> frame) {
  auto source = std::shared_ptr<Provenance>(new Provenance(frame));

  if (!universes_.count(source->universe()))
    return;
  auto universe = universes_.at(source->universe())->sourceUniverse(*source);

  /// 6.2.3 E1.31 Data Packet: Priority
  /// No priority outside the range of 0 to 200 shall be transmitted on
  /// the network.
  if (source->priority() > 200)
    frame->stream()->setstate(std::ios_base::failbit);

  /// 6.2.6 E1.31 Data Packet: Options
  /// Preview_Data: Bit 7 (most significant bit)
  /// This bit, when set to 1, indicates that the data in this packet is
  /// intended for use in visualization or media server preview applications and
  /// shall not be used to generate live output.
  if (source->isPreview())
    return;

  /// 6.2.6 E1.31 Data Packet: Options
  /// Stream_Terminated: Bit 6
  /// allow E1.31 sources to terminate transmission of a stream or of
  /// universe synchronization without waiting for a timeout to occur.
  /// Any property values in an E1.31 Data Packet containing this bit
  /// shall be ignored.
  if (source->isTerminated()) {
    universes_[source->universe()]->deleteSourceUniverse(*source);
    return;
  }

  /// 6.2.4.1 Synchronization Address Usage in an E1.31 Data Packet
  /// a value of 0 in the Synchronization Address indicates that the universe
  /// data is not synchronized.
  if (source->syncAddress() != 0)
      subscribe(source->syncAddress());

  // PDU data will be a block of DMP
  auto block = static_cast<ACN::PDU::Block<ACN::DMP::Pdu>*>(frame->data());
  for (auto const &dmp : *block->pdu)
    {
      /// 7.2 DMP Layer: Vector
      /// The DMP Layer's Vector shall be set to VECTOR_DMP_SET_PROPERTY, which
      /// indicates a DMP Set Property message by sources. Receivers shall
      /// discard the packet if the received value is not
      /// VECTOR_DMP_SET_PROPERTY.
      switch(dmp->vector()) {
        case ACN::DMP::SET_PROPERTY:
          universe->set(dmp, source);
          break;
        default:
          break;
        }
    }
}


/**
 * @brief Receiver::syncFrameHandler
 * @param frame
 */
void Receiver::syncFrameHandler(ACN::PDU::Message<EXTENDED::Pdu> frame)
{
  auto header = static_cast<EXTENDED::sync_header*>(frame->header());
  universes_.at(header->sync_address)->synchronize();
}


/**
 * @brief Receiver::discoveryFrameHandler
 * @param frame
 */
void Receiver::discoveryFrameHandler(ACN::PDU::Message<EXTENDED::Pdu> frame) {
  auto block = static_cast<ACN::PDU::Block<EXTENDED::DISCOVERY::Pdu>*>(frame->data());
  for(auto const &pdu : *block->pdu)
    {
      /// 8 Universe Discovery Layer
      /// Universe Discovery data only appears in E1.31 Universe Discovery
      /// Packets and shall not be included in E1.31 Data Packets or E1.31
      /// Synchronization Packets.
      switch(pdu->vector()) {
        case VECTOR_UNIVERSE_DISCOVERY_UNIVERSE_LIST:
          discoveryListHanlder(pdu);
          break;
        default:
          break;
        }
    }
}


/**
 * @brief Receiver::discoveryListHanlder
 * @param pdu
 */
void Receiver::discoveryListHanlder(ACN::PDU::Message<EXTENDED::DISCOVERY::Pdu> pdu) {
  auto data = static_cast<EXTENDED::DISCOVERY::discovery_list_data*>(pdu->data());
  for (auto& f : data->found)
    for (const auto &cb : discoveryCallbacks_)
      cb(std::make_shared<EXTENDED::DISCOVERY::discoveredUniverse>(f));
}


}; // SACN
