#include "ConfigRsuSimulatorLayerFactory.hh"

#include "loggers.hh"

#include "ItsRSUsSimulator_TestSystem.hh"

#include "LibCommon_BasicTypesAndValues.hh"

#include "uppertester_cam_codec.hh"
#include "uppertester_geonetworking_codec.hh"

#include "LibItsCam_EncdecDeclarations.hh"

ConfigRsuSimulatorLayer::ConfigRsuSimulatorLayer(const std::string & p_type, const std::string & param) : t_layer<ItsRSUsSimulator__TestSystem::ConfigRsuSimulatorPort>(p_type), _params(), _codec(), _codec_cam() {
  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;
  }

  send_data(data, _params);
}

void ConfigRsuSimulatorLayer::sendMsg(const LibItsGeoNetworking__TypesAndValues::UtGnResults& send_par, params& params) {
  loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::sendMsg: ", send_par);

  TTCN_Buffer encoding_buffer;
  if (send_par.ischosen(LibItsGeoNetworking__TypesAndValues::UtGnResults::ALT_utGnInitializeResult)) {
    encoding_buffer.put_c(0x01/*static_cast<const unsigned char>(uppertester_geonetworking_codec::c_utGnInitializeResult)*/);
    encoding_buffer.put_c((unsigned char)static_cast<const boolean>(send_par.utGnInitializeResult()));
  } else if (send_par.ischosen(LibItsGeoNetworking__TypesAndValues::UtGnResults::ALT_utGnTriggerResult)) {
    encoding_buffer.put_c(0x41/*static_cast<const unsigned char>(uppertester_geonetworking_codec::c_utGnTriggerResult)*/);
    encoding_buffer.put_c((unsigned char)static_cast<const boolean>(send_par.utGnTriggerResult()));
  } else {
    loggers::get_instance().warning("ConfigRsuSimulatorLayer::sendMsg: Unsupported UtGnResults variant");
    return;
  }

  OCTETSTRING os(encoding_buffer.get_len(), encoding_buffer.get_data());
  send_data(os, _params);
}

void ConfigRsuSimulatorLayer::sendMsg(const LibItsCam__TypesAndValues::UtCamResults& send_par, params& params) {
  loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::sendMsg: ", send_par);

  TTCN_Buffer encoding_buffer;
  if (send_par.ischosen(LibItsCam__TypesAndValues::UtCamResults::ALT_utCamInitializeResult)) {
    encoding_buffer.put_c(0x01/*static_cast<const unsigned char>(uppertester_cam_codec::c_utCamInitializeResult)*/);
    encoding_buffer.put_c((unsigned char)static_cast<const boolean>(send_par.utCamInitializeResult()));
  } else if (send_par.ischosen(LibItsCam__TypesAndValues::UtCamResults::ALT_utCamTriggerResult)) {
    encoding_buffer.put_c(0x21/*static_cast<const unsigned char>(uppertester_cam_codec::c_utCamTriggerResult)*/);
    encoding_buffer.put_c((unsigned char)static_cast<const boolean>(send_par.utCamTriggerResult()));
  } else {
    loggers::get_instance().warning("ConfigRsuSimulatorLayer::sendMsg: Unsupported UtCamResults variant");
    return;
  }

  OCTETSTRING os(encoding_buffer.get_len(), encoding_buffer.get_data());
  send_data(os, _params);
}

void ConfigRsuSimulatorLayer::sendMsg(const LibItsCam__TypesAndValues::UtCamEventInd& send_par, params& params) {
  loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::sendMsg: ", send_par);

  TTCN_Buffer encoding_buffer;
  encoding_buffer.put_c(0x23/*static_cast<const unsigned char>(uppertester_cam_codec::c_utCamEventInd)*/);
  BITSTRING bs = LibItsCam__EncdecDeclarations::fx__enc__CAM(send_par.camMsg());
  encoding_buffer.put_s(bs.lengthof(), static_cast<const unsigned char*>(bs));
  OCTETSTRING os(encoding_buffer.get_len(), encoding_buffer.get_data());
  send_data(os, _params);
}

void ConfigRsuSimulatorLayer::sendMsg(const LibItsDenm__TypesAndValues::UtDenmResults& send_par, params& params) {
  loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::sendMsg: ", send_par);

  TTCN_Buffer encoding_buffer;
  if (send_par.ischosen(LibItsDenm__TypesAndValues::UtDenmResults::ALT_utDenmInitializeResult)) {
    encoding_buffer.put_c(0x01/*static_cast<const unsigned char>(uppertester_denm_codec::c_utDenmInitializeResult)*/);
    encoding_buffer.put_c((unsigned char)static_cast<const boolean>(send_par.utDenmInitializeResult()));
  } else {
    loggers::get_instance().warning("ConfigRsuSimulatorLayer::sendMsg: Unsupported UtDenmResults variant");
    return;
  }

  OCTETSTRING os(encoding_buffer.get_len(), encoding_buffer.get_data());
  send_data(os, _params);
}

void ConfigRsuSimulatorLayer::send_data(OCTETSTRING& data, params& params) {
  loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::send_data: ", data);
  
  send_to_all_layers(data, params);
}

void ConfigRsuSimulatorLayer::receive_data(OCTETSTRING& data, params& params)
{ // FIXME To be moved into ConfigRsuSimulatorCodec
  loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::receive_data: ", data);

  unsigned char id = *(static_cast<const unsigned char*>(data));
  if (id == 0x00) { // Receive an UtxxInitialise
    process_utinitialize_data(data, params);
  } else if (id == 0x30/*uppertester_cam_codec::c_utCamChangeCurvature*/) {
    process_ut_cam_changecurvature_data(data, params);
  } else if (id == 0x31/*uppertester_cam_codec::c_utCamChangeSpeed*/) {
    process_ut_cam_changespeed_data(data, params);
  } else if (id == 0x34/*uppertester_cam_codec::c_utCamChangeHeading*/) {
    process_ut_cam_changeheading_data(data, params);
  } else if ((id >= 0x50) && (id <= 0x54)) { // Receive an UtGnTrigger
    process_ut_geonetworking_trigger(data, params);
  } else {
    loggers::get_instance().warning("ConfigRsuSimulatorLayer::receive_data: Unsupported tag %02x", id);
  }
  
}

int ConfigRsuSimulatorLayer::process_utinitialize_data(const OCTETSTRING& data, params& params) {
  loggers::get_instance().log(">>> ConfigRsuSimulatorLayer::process_utinitialize_data");
  
  params::const_iterator it = _params.find("ut");
  if (it == _params.cend()) {
    loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_utinitialize_data: CF layer's ut parameter is missing");
    return -1;
  }

  if (_params[std::string("ut")].compare("gn") == 0) {
    OCTETSTRING hashedId(data.lengthof() - 1,  1 + static_cast<const unsigned char*>(data));
    LibItsGeoNetworking__TypesAndValues::UtGnInitialize p(hashedId);
    // Pass it to the ports if any
    to_all_upper_ports(p, params);
  } else if (_params[std::string("ut")].compare("cam") == 0) {
    OCTETSTRING hashedId(data.lengthof() - 1,  1 + static_cast<const unsigned char*>(data));
    LibItsCam__TypesAndValues::UtCamInitialize p(hashedId);
    // Pass it to the ports if any
    to_all_upper_ports(p, params);
  } else if (_params[std::string("ut")].compare("denm") == 0) {
    OCTETSTRING hashedId(data.lengthof() - 1,  1 + static_cast<const unsigned char*>(data));
    LibItsDenm__TypesAndValues::UtDenmInitialize p(hashedId);
    // Pass it to the ports if any
    to_all_upper_ports(p, params);
  } else {
    loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_utinitialize_data: Unsupported protocol");
    return -1;
  }

  return 0;
}

int ConfigRsuSimulatorLayer::process_ut_cam_changespeed_data(const OCTETSTRING& data, params& params) {
  loggers::get_instance().log(">>> ConfigRsuSimulatorLayer::process_ut_cam_changespeed_data");

  params::const_iterator it = _params.find("ut");
  if (it == _params.cend()) {
    loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_cam_changespeed_data: CF layer's ut parameter is missing");
    return -1;
  }

  if (_params[std::string("ut")].compare("cam") == 0) {
    OCTETSTRING speed(data.lengthof() - 1,  1 + static_cast<const unsigned char*>(data));
    LibItsCam__TypesAndValues::UtCamTrigger p;
    p.changeSpeed() = oct2int(speed);
    // Pass it to the ports if any
    to_all_upper_ports(p, params);
  } else {
    loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_cam_changespeed_data: Unsupported protocol");
    return -1;
  }

  return 0;
}

int ConfigRsuSimulatorLayer::process_ut_cam_changecurvature_data(const OCTETSTRING& data, params& params) {
  loggers::get_instance().log(">>> ConfigRsuSimulatorLayer::process_ut_cam_changecurvature_data");

  params::const_iterator it = _params.find("ut");
  if (it == _params.cend()) {
    loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_cam_changecurvature_data: CF layer's ut parameter is missing");
    return -1;
  }

  if (_params[std::string("ut")].compare("cam") == 0) {
    OCTETSTRING curvature(data.lengthof() - 1,  1 + static_cast<const unsigned char*>(data));
    LibItsCam__TypesAndValues::UtCamTrigger p;
    p.changeCurvature() = oct2int(curvature);
    // Pass it to the ports if any
    to_all_upper_ports(p, params);
  } else {
    loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_cam_changecurvature_data: Unsupported protocol");
    return -1;
  }

  return 0;
}

int ConfigRsuSimulatorLayer::process_ut_cam_changeheading_data(const OCTETSTRING& data, params& params) {
  loggers::get_instance().log(">>> ConfigRsuSimulatorLayer::process_ut_cam_changeheading_data");

  params::const_iterator it = _params.find("ut");
  if (it == _params.cend()) {
    loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_cam_changeheading_data: CF layer's ut parameter is missing");
    return -1;
  }

  if (_params[std::string("ut")].compare("cam") == 0) {
    OCTETSTRING heading(data.lengthof() - 1,  1 + static_cast<const unsigned char*>(data));
    LibItsCam__TypesAndValues::UtCamTrigger p;
    p.changeHeading() = oct2int(heading);
    // Pass it to the ports if any
    to_all_upper_ports(p, params);
  } else {
    loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_cam_changeheading_data: Unsupported protocol");
    return -1;
  }

  return 0;
}

int ConfigRsuSimulatorLayer::process_ut_geonetworking_trigger(const OCTETSTRING& data, params& params) {
  loggers::get_instance().log(">>> ConfigRsuSimulatorLayer::process_ut_geonetworking_trigger");

  params::const_iterator it = _params.find("ut");
  if (it == _params.cend()) {
    loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_geonetworking_trigger: CF layer's ut parameter is missing");
    return -1;
  }

  if (_params[std::string("ut")].compare("gn") == 0) {
    unsigned char msg_id = *static_cast<const unsigned char*>(data);
    loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_geonetworking_trigger: msg_id=%02x", msg_id);
    OCTETSTRING payload(data.lengthof() - 1,  1 + static_cast<const unsigned char*>(data));
    loggers::get_instance().log_msg("ConfigRsuSimulatorLayer::process_ut_geonetworking_trigger: payload:", payload);
    TTCN_EncDec::clear_error();
    TTCN_Buffer decoding_buffer(payload);

    LibItsGeoNetworking__TypesAndValues::UtGnTrigger p;
    if (msg_id == 0x50/*uppertester_geonetworking_codec::c_utGnTrigger_GeoUnicast*/) {
      LibItsGeoNetworking__TypesAndValues::GenerateGeoUnicastMessage g;
      g.decode(*g.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_RAW);
      g.payload() = OCTETSTRING(g.payload().lengthof() - 2, static_cast<const unsigned char*>(g.payload()));
      p.geoUnicast() = g;
    } else if (msg_id == 0x51/*uppertester_geonetworking_codec::c_utGnTrigger_GeoBroadcast*/) {
      LibItsGeoNetworking__TypesAndValues::GenerateGeoBroadcastMessage g;
      g.decode(*g.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_RAW);
      g.payload() = OCTETSTRING(g.payload().lengthof() - 2, static_cast<const unsigned char*>(g.payload()));
      p.geoBroadcast() = g;
    }
    // Pass it to the ports if any
    to_all_upper_ports(p, params);
  } else {
    loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_geonetworking_trigger: Unsupported protocol");
    return -1;
  }

  return 0;
}

ConfigRsuSimulatorLayerFactory ConfigRsuSimulatorLayerFactory::_f;
