#include "LocationTable.hh"

#include "GeoNetworkingTypes.hh"

#include "loggers.hh"

using namespace LibItsGeoNetworking__TypesAndValues;

void LocationTable::add_entry(const LibItsGeoNetworking__TypesAndValues::LongPosVector& p_long_pos_vector) {
  loggers::get_instance().log_msg(">>> LocationTable::add_entry:", p_long_pos_vector);

  std::map<OCTETSTRING, std::shared_ptr<LibItsGeoNetworking__TypesAndValues::LongPosVector>>::const_iterator it = _entries_by_mids.find(p_long_pos_vector.gnAddr().mid());
  if (it == _entries_by_mids.cend()) { // Not found
    // Add it
    loggers::get_instance().log("LocationTable::add_entry: Create new entry");
    std::shared_ptr<LibItsGeoNetworking__TypesAndValues::LongPosVector> lpv(new LibItsGeoNetworking__TypesAndValues::LongPosVector(p_long_pos_vector));
    _entries_by_mids.insert(std::pair<OCTETSTRING, std::shared_ptr<LibItsGeoNetworking__TypesAndValues::LongPosVector>>(p_long_pos_vector.gnAddr().mid(), lpv));
    _entries_by_times.insert(std::pair<unsigned long, std::shared_ptr<LibItsGeoNetworking__TypesAndValues::LongPosVector>>(static_cast<unsigned long>(p_long_pos_vector.timestamp__().get_long_long_val()), lpv));
  } else {
    // TODO Update the timestamp
  }
} // End of add_entry method

const LibItsGeoNetworking__TypesAndValues::LongPosVector* LocationTable::get_entry(const OCTETSTRING & p_mid) const {
  // Sanity check
  if (_entries_by_times.empty() || (p_mid.lengthof() != 8)) {
    return nullptr;
  }

  std::map<OCTETSTRING, std::shared_ptr<LibItsGeoNetworking__TypesAndValues::LongPosVector>>::const_iterator it = _entries_by_mids.find(p_mid);
  if (it == _entries_by_mids.cend()) { // Not found
    return nullptr;
  }

  return it->second.get();
} // End of get_entry method
