/*
  universe.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 "universe.h"

namespace SACN {

/**
 * @brief Universe::Universe
 */
Universe::Universe()
    : DMX::Universe(E131_NETWORK_DATA_LOSS_TIMEOUT)
    , ACN::DMP::Device()
{
  sync_data_.clear();
}


/**
 * @brief Universe::set
 * @param dmp
 * @param source
 */
void Universe::set(std::shared_ptr<ACN::DMP::Pdu> dmp,
                   std::shared_ptr<Provenance> source)
{
  /// 7.3 Address Type and Data Type
  /// Sources shall set the DMP Layer's Address Type and Data Type to 0xa1.
  /// Receivers shall discard the packet if the received value is not 0xa1.
  if (!dmp->header())
    return;
  auto type = static_cast<ACN::DMP::address_type*>(dmp->header());
  if (type->relative) return;
  if (type->type != ACN::DMP::ARRAY) return;
  if (type->width != ACN::DMP::TWO) return;

  // only act on the first property pair in the data
  if (!dmp->data())
    return;
  auto set_data = static_cast<ACN::DMP::address_pair_list*>(dmp->data());
  const auto& [range, data] = set_data->properties.front();

  /// 7.4 First Property Address
  /// Sources shall set the DMP Layer's First Property Address to 0x0000.
  /// Receivers shall discard the packet if the received value is not 0x0000.
  if (range.address != 0)
    return;

  /// 7.5 Address Increment
  /// Sources shall set the DMP Layer's Address Increment to 0x0001.
  /// Receivers shall discard the packet if the received value is not 0x0001.
  if (range.incriment != 1)
    return;

  /// 7.6 Property Value Count
  /// The DMP Layer's Property Value Count is used to encode the number of
  /// DMX512-A [DMX] Slots (including the START Code slot).
  if (range.count < 1 || range.count > 513)
    return;

  setProvenance(source);

  /// 7.7 Property Values (DMX512-A Data)
  /// The DMP Layer's Property values field is used to encode the
  /// DMX512-A [DMX] START Code and data.

  /// 6.2.4.1 If a receiver is presented with an E1.31 Data Packet containing a
  /// Synchronization Address of 0, it shall discard any data waiting to be
  /// processed and immediately act on that Data Packet.
  if (source->syncAddress() == 0)
    {
      sync_data_.clear();
      DMX::Universe::setData(data);
    }
  else
    sync_data_ = data;
}


/**
 * @brief Universe::setSource
 * @param source
 */
void Universe::setProvenance(std::shared_ptr<Provenance> source)
{
  provenance_ = source;
}


/**
 * @brief Universe::isSyncronized
 * @return
 */
bool Universe::isSyncronized() const
{
  return (sync_data_.size() > 0);
};


/**
 * @brief Universe::source
 * @return
 */
std::shared_ptr<Provenance> Universe::source() const
{
  return provenance_;
}


/**
 * @brief Universe::slot
 * @param addr
 * @return
 */
uint8_t Universe::slot(const uint16_t addr)
{
  /// 6.2.6 E1.31 Data Packet: Options
  /// Force_Synchronization: Bit 5
  /// This bit indicates whether to lock or revert to an unsynchronized state
  /// when synchronization is lost. When set to 0, components that had been
  /// operating in a synchronized state shall not update with any new packets
  /// until synchronization resumes. When set to 1, once synchronization has
  /// been lost, components that had been operating in a synchronized state need
  /// not wait for a new E1.31 Synchronization Packet in order to update to the
  /// next E1.31 Data Packet.
  if (isSyncronized() && source()->isForced() && rxRate() == 0)
    synchronize();

  return DMX::Universe::slot(addr);
}


/**
 * @brief Universe::synchronize
 */
void Universe::synchronize()
{
  if (!isSyncronized())
    return;

  DMX::Universe::setData(sync_data_);
  sync_data_.clear();
}

};  // namespace SACN
