/*!
 * \file      ngap_layer.cc
 * \brief     CC file for NGAP protocol layer.
 * \author    ETSI TTF041
 * \copyright ETSI Copyright Notification
 *            No part may be reproduced except as authorized by written permission.
 *            The copyright and the foregoing restriction extend to reproduction in all media.
 *            All rights reserved.
 * \version   0.1
 */

#include "ngap_types.hh"

#include "NGAP_TestSystem.hh"

#include "ngap_layer_factory.hh"

#include "registration.hh"

#include "loggers.hh"

ngap_layer::ngap_layer(const std::string &p_type, const std::string &param) : t_layer<LibNGAP__Interface::NGAPPort>(p_type), _params(), _codec() {
  loggers::get_instance().log(">>> ngap_layer::ngap_layer: %s, %s", to_string().c_str(), param.c_str());
  // Setup parameters
  params::convert(_params, param);

  // Register this object for AdapterControlPort
  loggers::get_instance().log("ngap_layer::ngap_layer: Register %s/%p", p_type.c_str(), this);
  registration<ngap_layer>::get_instance().add_item(p_type, this);
}

void ngap_layer::sendMsg(const NGAP__PDU__Descriptions::NGAP__PDU& p, params &params) {
  loggers::get_instance().log_msg(">>> ngap_layer::sendMsg: ", p);

  // Encode NGAP PDU
  OCTETSTRING data;
   if (_codec.encode(p, data) < 0) {
      loggers::get_instance().warning("ngap_layer::sendMsg: Encoding failure");
      data=int2oct(0,1);
      //return;
   }
   loggers::get_instance().log_msg(">>> ngap_layer::sendMsg . encoded: ", data);

  send_data(data, _params);
}

void ngap_layer::send_data(OCTETSTRING &data, params &p_params) {
  loggers::get_instance().log_msg(">>> ngap_layer::send_data: ", data);

  send_to_all_layers(data, p_params);
}

void ngap_layer::receive_data(OCTETSTRING &data, params &p_params) {
  loggers::get_instance().log_msg(">>> ngap_layer::receive_data: ", data);

  // Decode the payload
  NGAP__PDU__Descriptions::NGAP__PDU p;
  _codec.decode(data, p);
  if (!p.is_bound()) {
    // Discard it
    return;
  } // else, continue

  // Pass it to the ports if any
  to_all_upper_ports(p, p_params);
}

ngap_layer_factory ngap_layer_factory::_f;
