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

namespace sACN {

/**
 * @brief MergeProxyUniverse::MergeProxyUniverse
 */
ArbitratingUniverse::ArbitratingUniverse()
      : sACN::Universe()
      , expectedUniverse(0)
      , HoldLastLook(true)
{
}


/**
 * @brief MergeProxyUniverse::~MergeProxyUniverse
 */
ArbitratingUniverse::~ArbitratingUniverse()
{
}


/**
 * @brief ArbitratingUniverse::setHoldLastLook
 * @param state
 */
void ArbitratingUniverse::setHoldLastLook(const bool state)
{
  HoldLastLook = state;
}


/**
 * @brief ArbitratingUniverse::getHoldLastLook
 * @return
 */
bool ArbitratingUniverse::getHoldLastLook() const
{
  return HoldLastLook;
}


const std::vector<DATA::data_header> ArbitratingUniverse::sources() const
{
  std::vector<DATA::data_header> keys;
  for (const auto& [key, _] : sources_)
    keys.push_back(key);
  return keys;
}


/**
 * @brief MergeProxyUniverse::sourceUniverse
 * @param src
 * @return
 */
std::shared_ptr<Universe> ArbitratingUniverse::sourceUniverse(const DATA::data_header &src)
{
  if (!hasSourceUniverse(src))
    return nullptr;

  return sources_.at(src);
}


/**
 * @brief MergeProxyUniverse::hasSourceUniverse
 * @param src
 * @return
 */
bool ArbitratingUniverse::hasSourceUniverse(const DATA::data_header& src) const
{
  return (sources_.count(src));
}


std::shared_ptr<Universe> ArbitratingUniverse::addNewSource(const DATA::data_header &src)
{
  sources_.emplace(src, std::make_shared<Universe>());
  auto token = sources_.at(src)->onData(std::bind(&sACN::ArbitratingUniverse::dataChangedNotifier,
                                                  this, std::placeholders::_1));
  source_data_tokens.push_back(token);
  doListChangeCallbacks();

  return sources_.at(src);
}


/**
 * @brief MergeProxyUniverse::deleteSourceUniverse
 * @param src
 */
void ArbitratingUniverse::deleteSourceUniverse(const DATA::data_header& src)
{
  if (!hasSourceUniverse(src))
    return;

  /// \todo also erase token for data change callbacks

  sources_.erase(src);
  doListChangeCallbacks();
}


/**
 * @brief MergeProxyUniverse::dataChangedNotifier
 * @param dmx
 */
void ArbitratingUniverse::dataChangedNotifier(DMX::Universe* dmx)
{
  auto sacn = static_cast<sACN::Universe*>(dmx);
  auto universe = dominant_();
  if (!universe)
    return;
  if (sacn->provenance() == universe->provenance())
    doDataCallbacks();
}


/**
 * @brief ArbitratingUniverse::onSourceListChange
 * @param cb
 * @return
 */
std::shared_ptr<void> ArbitratingUniverse::onSourceListChange(std::function<void()> cb)
{
  // wrap the callback with a shared pointer
  auto sp = std::make_shared<std::function<void()>>(std::move(cb));
  // add callback to list (as a weak pointer)
  cb_sourceListChange.push_back(sp);
  // return token that caller must keep throughout it's scope
  return sp;
}


/**
 * @brief ArbitratingUniverse::doListChangeCallbacks
 */
void ArbitratingUniverse::doListChangeCallbacks()
{
  for (auto it = cb_sourceListChange.begin(); it != cb_sourceListChange.end();)
  {
    if (auto sp = it->lock())
    { // if the caller is still holding the token
      (*sp)();
      ++it;
    }
    else
    { // or remove the callback
      it = cb_sourceListChange.erase(it);
    }
  }
}


/**
 * @brief MergeProxyUniverse::isSyncronized
 * @return
 */
bool ArbitratingUniverse::isSyncronized()
{
  auto universe = dominant_();
  if (!universe)
    return false;
  return universe->isSyncronized();
}


/**
 * @brief MergeProxyUniverse::provenance
 * @return
 */
std::shared_ptr<DATA::data_header> ArbitratingUniverse::provenance()
{
  auto universe = dominant_();
  if (universe)
    return universe->provenance();

  auto prov = std::make_shared<DATA::data_header>();
  prov->universe = expectedUniverse;
  prov->priority = 255; // invalid data
  prov->source_name = "Pending data...";
  return prov;
}


/**
 * @brief MergeProxyUniverse::set
 * @param pdu
 * @param src
 */
void ArbitratingUniverse::set(std::shared_ptr<ACN::DMP::Pdu> pdu,
                             std::shared_ptr<DATA::data_header> src)
{
  if (expectedUniverse != 0 &&
      src->universe != expectedUniverse)
    return;

  if (!sources_.count(*src))
    addNewSource(*src);

  sources_.at(*src)->set(pdu, src);
}


/**
 * @brief ArbitratingUniverse::synchronize
 * @param sequence_number
 */
void ArbitratingUniverse::synchronize(uint8_t sequence_number)
{
  for ( auto& [_, uni] : sources_)
    uni->synchronize(sequence_number);
}


bool ArbitratingUniverse::isEditable() const {
  return false;
}


uint16_t ArbitratingUniverse::activeSlots()
{
  auto universe = dominant_();
  if (!universe)
    return 0;
  return universe->activeSlots();
}


/**
 * @brief MergeProxyUniverse::slot
 * @param s
 * @return
 */
uint8_t ArbitratingUniverse::slot(const uint16_t s)
{
  auto universe = dominant_();
  if (!universe)
    return 0;
  return universe->slot(s);
}


/**
 * @brief MergeProxyUniverse::rxRate
 * @return
 */
double ArbitratingUniverse::rxRate()
{
  auto universe = dominant_();
  if (!universe)
    return 0.0;
  return universe->rxRate();
}


/**
 * @brief MergeProxyUniverse::dominant_
 * @return
 */
std::shared_ptr<Universe> ArbitratingUniverse::dominant_()
{
  bool sourceListChanged = false;
  std::shared_ptr<Universe> ret = nullptr;

  for(auto it = sources_.begin(); it != sources_.end(); )
  {
    auto universe = it->second;

    if (!ret && HoldLastLook)
    { // anything is better than nothing
      ++it;
      ret = universe;
      continue;
    }

      auto age = universe->rxAge();

      if (age > E131_NETWORK_DATA_LOSS_TIMEOUT)
      { // clean up zombie universes
        it = sources_.erase(it);
        sourceListChanged = true;
        continue;
      }

      if (age > DMX::E111_DATA_LOSS_TIMEOUT)
      {
        ++it;
        continue;  // stale universes cannot be dominant
      }

      if (universe->provenance()->priority > ret->provenance()->priority)
        ret = universe; // rank by provenance

      ++it;
  }

  if (sourceListChanged)
    doListChangeCallbacks();

  return ret;
}

} // namespace SACN
