#include "InfoEvent.hpp"

#include <iostream>
#include <sys/socket.h>

#include "packets/info/InfoPacketData.hpp"


namespace drp::event {


void InfoEvent::handle(
    Context& context,
    const packet::base::PacketContent& content,
    const sockaddr_storage& fromAddress,
    const socklen_t fromAddressLength
) {
    std::cout << "[Event - Info] Received peer information." << std::endl;

    // get the peer information
    const auto packetData = packet::info::InfoPacketData::fromGeneric(content);
    const Peer peer = packetData.peer;

    // check if the peer address is already in the map
    const auto iterator = context.remotePeers.find(peer.id);

    std::shared_ptr<RemotePeer> remotePeer;
    if (iterator == context.remotePeers.end()) {
        // if not found, create a new peer
        remotePeer = std::make_shared<RemotePeer>();
        remotePeer->address = fromAddress;
        remotePeer->addressLength = fromAddressLength;
        // update the latest discovery time
        context.latestPeerDiscovery = std::chrono::high_resolution_clock::now();
    } else {
        // get the peer
        remotePeer = iterator->second;
    }

    // TODO(Faraphel): interpret the timestamp and calculate average ping

    // save it in the peers list
    remotePeer->information = peer;
    context.remotePeers[peer.id] = remotePeer;
}


}
