#include "CAMLayer.hh"
#include "CAMTypes.hh"

#include "loggers.hh"

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

void CAMLayer::sendMsg(const LibItsCam__TestSystem::CamReq& p, Params& params){
  loggers::get_instance().log(">>> CAMLayer::sendMsg");

  // Encode CAM 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 CAMLayer::sendData(OCTETSTRING& data, Params& params) {
  loggers::get_instance().log_msg(">>> CAMLayer::sendData: ", data);
  params.log();  
  sendToAllLayers(data, params);
}

void CAMLayer::receiveData(OCTETSTRING& data, Params& params)
{
  loggers::get_instance().log_msg(">>> CAMLayer::receiveData: ", data);
  // Decode the payload
  LibItsCam__TestSystem::CamInd 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 CAMFactory : public LayerFactory {
  static CAMFactory _f;
public:
  CAMFactory();
  virtual Layer * createLayer(const std::string &  type, const std::string &  param);
};

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

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

CAMFactory CAMFactory::_f;
