#include "DENMLayer.hh"
#include "DENMTypes.hh"

#include "loggers.hh"

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

void DENMLayer::sendMsg(const LibItsDenm__TestSystem::DenmReq& p, Params& params){
  loggers::get_instance().log(">>> DENMLayer::sendMsg");

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

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

void DENMLayer::receiveData(OCTETSTRING& data, Params& params)
{
  loggers::get_instance().log_msg(">>> DENMLayer::receiveData: ", data);
  // Decode the payload
  LibItsDenm__TestSystem::DenmInd p;
  _codec.decode(data, p.msgIn());
  
  // Add lower layers parameters
  //  const OPTIONAL<INTEGER>& par_gnNextHeader,
  //  const OPTIONAL<INTEGER>& par_gnHeaderType,
  //  const OPTIONAL<INTEGER>& par_gnHeaderSubtype,
  //  const OPTIONAL<INTEGER>& par_gnLifetime,
  //  const OPTIONAL<INTEGER>& par_gnTrafficClass,
  //  const OPTIONAL<INTEGER>& par_btpDestinationPort,
  //  const OPTIONAL<INTEGER>& par_btpInfo,
  //  const OPTIONAL<BITSTRING>& par_ssp,
  //  const OPTIONAL<INTEGER>& par_its__aid);
  
  // Pass it to the ports if amy
  toAllUpperPorts(p, params);
}

class DENMFactory : public LayerFactory {
  static DENMFactory _f;
public:
  DENMFactory();
  virtual Layer * createLayer(const std::string &  type, const std::string &  param);
};

DENMFactory::DENMFactory(){
  // Register factory
  loggers::get_instance().log(">>> DENMFactory::DENMFactory");
  LayerStackBuilder::RegisterLayerFactory("DENM", this);
}

Layer * DENMFactory::createLayer(const std::string & p_type, const std::string & param){
  return new DENMLayer(p_type, param);
}

DENMFactory DENMFactory::_f;
