#include "UpperTesterGnFactory.hh"

#include "UpperTesterTypes.hh"

#include "loggers.hh"

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

void UpperTesterGnLayer::sendMsg(const LibItsGeoNetworking__TypesAndValues::UtGnInitialize& send_par, Params& params){
  loggers::get_instance().log_msg(">>> UpperTesterGnLayer::sendMsg", send_par);

  // Encode UpperTester PDU
  OCTETSTRING data;
  _codec.encode((const Record_Type &)send_par, data);
  // Update parameters
  Params par(params); // FIXME Review all const Param& in method declarations
  sendData(data, params);
}

void UpperTesterGnLayer::sendMsg(const LibItsGeoNetworking__TypesAndValues::UtGnChangePosition& send_par, Params& params)
{
  loggers::get_instance().log_msg(">>> UpperTesterGnLayer::sendMsg", send_par);

  // Encode UpperTester PDU
  OCTETSTRING data;
  _codec.encode((const Record_Type &)send_par, data);
  // Update parameters
  Params par(params); // FIXME Review all const Param& in method declarations
  sendData(data, params);
}

void UpperTesterGnLayer::sendMsg(const LibItsGeoNetworking__TypesAndValues::UtGnTrigger& send_par, Params& params)
{
  loggers::get_instance().log_msg(">>> UpperTesterGnLayer::sendMsg", send_par);

  // Encode UpperTester PDU
  OCTETSTRING data;
  _codec.encode((const Record_Type &)send_par, data);
  // Update parameters
  Params par(params); // FIXME Review all const Param& in method declarations
  sendData(data, params);
}

void UpperTesterGnLayer::sendMsg(const LibItsGeoNetworking__TypesAndValues::UtAutoInteropTrigger& send_par, Params& params)
{
  loggers::get_instance().log_msg(">>> UpperTesterGnLayer::sendMsg", send_par);

  // Encode UpperTester PDU
  OCTETSTRING data;
  _codec.encode((const Record_Type &)send_par, data);
  // Update parameters
  Params par(params); // FIXME Review all const Param& in method declarations
  sendData(data, params);
}

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

void UpperTesterGnLayer::receiveData(OCTETSTRING& data, Params& params)
{
  loggers::get_instance().log_msg(">>> UpperTesterGnLayer::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);
  }
}

UpperTesterGnFactory UpperTesterGnFactory::_f;
