#include "ConfigRsuSimulatorLayerFactory.hh"

#include "loggers.hh"

#include "ItsRSUsSimulator_TestSystem.hh"

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

void ConfigRsuSimulatorLayer::sendMsg(const ItsRSUsSimulator__TestSystem::CfInitialize& send_par, Params& params){
  loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::sendMsg: ", send_par);
  
  // Encode ConfigRsuSimulator PDU
  OCTETSTRING data;
  if (_codec.encode(static_cast<const Record_Type&>(send_par), data) == -1) {
    loggers::get_instance().warning("ConfigRsuSimulatorLayer::sendMsg: Encoding failure");
    return;
  }

  sendData(data, _params);
}

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

void ConfigRsuSimulatorLayer::receiveData(OCTETSTRING& data, Params& params)
{
  loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::receiveData: ", data);
  
  // Sanity check
  if (*(static_cast<const unsigned char*>(data)+ 1) != 0x02) { // Check that received packet has CA message id - See ETSI TS 102 894
    // Not a ConfigRsuSimulator message, discard it
    loggers::get_instance().warning("ConfigRsuSimulatorLayer::receiveData: Wrong message id: 0x%02x", *(static_cast<const unsigned char*>(data)+ 1));
    return;
  }
  
  // Decode the payload
  BOOLEAN p;
  /*_codec.decode(data, p);
  if (!p.msgIn().is_bound()) {
    // Discard it
    return;
    }*/ // else, continue
  
  // Pass it to the ports if amy
  toAllUpperPorts(p, params);
}

ConfigRsuSimulatorLayerFactory ConfigRsuSimulatorLayerFactory::_f;
