#include "UpperTesterIvimFactory.hh"

#include "UpperTesterTypes.hh"

#include "loggers.hh"

UpperTesterIvimLayer::UpperTesterIvimLayer(const std::string & p_type, const std::string & param) : TLayer<LibItsIvim__TestSystem::UpperTesterPort>(p_type), _params(), _codec() {
  loggers::get_instance().log(">>> UpperTesterIvimLayer::UpperTesterIvimLayer: %s, %s", to_string().c_str(), param.c_str());
  // Setup parameters
  Params::convert(_params, param);
}

void UpperTesterIvimLayer::sendMsg(const LibItsIvim__TypesAndValues::UtIvimInitialize& send_par, Params& params){
  loggers::get_instance().log_msg(">>> UpperTesterIvimLayer::sendMsg", send_par);

  // Encode UpperTester PDU
  OCTETSTRING data;
  _codec.encode((const Record_Type &)send_par, data);
  // Update parameters
  sendData(data, params);
}

void UpperTesterIvimLayer::sendMsg(const LibItsIvim__TypesAndValues::UtIvimTrigger& send_par, Params& params)
{
  loggers::get_instance().log_msg(">>> UpperTesterIvimLayer::sendMsg", send_par);

  // Encode UpperTester PDU
  OCTETSTRING data;
  _codec.encode((const Record_Type &)send_par, data);
  // Update parameters
  sendData(data, params);
}

void UpperTesterIvimLayer::sendMsg(const LibItsIvim__TypesAndValues::UtIvimUpdate& send_par, Params& params)
{
  loggers::get_instance().log_msg(">>> UpperTesterIvimLayer::sendMsg", send_par);

  // Encode UpperTester PDU
  OCTETSTRING data;
  _codec.encode(send_par, data);
  // Update parameters
  sendData(data, params);
}

void UpperTesterIvimLayer::sendMsg(const LibItsIvim__TypesAndValues::UtIvimTermination& send_par, Params& params)
{
  loggers::get_instance().log_msg(">>> UpperTesterIvimLayer::sendMsg", send_par);

  // Encode UpperTester PDU
  OCTETSTRING data;
  _codec.encode(send_par, data);
  // Update parameters
  sendData(data, params);
}

void UpperTesterIvimLayer::sendData(OCTETSTRING& data, Params& params) {
  loggers::get_instance().log_msg(">>> UpperTesterIvimLayer::sendData: ", data);
  //params.log();
  sendToAllLayers(data, params);
}

void UpperTesterIvimLayer::receiveData(OCTETSTRING& data, Params& params)
{
  loggers::get_instance().log_msg(">>> UpperTesterIvimLayer::receiveData: ", data);
 
  std::unique_ptr<Base_Type> r = _codec.decode(data);
  if (r.get() != nullptr) {
    // Pass it to the ports if amy
    toAllUpperPorts(*r, params);
  }
}

UpperTesterIvimFactory UpperTesterIvimFactory::_f;
