#include "InfoEvent.hpp"

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

#include "packets/info/InfoPacketData.hpp"


namespace drp::event {


void InfoEvent::handle(
    Context& context,
    std::vector<std::uint8_t>& data,
    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::deserialize(data);
    const Peer packetPeer = packetData.peer;

    // check if the peer address is already in the map
    const auto itRemotePeer = std::ranges::find_if(
        context.remotePeers,
        [&](const auto& remotePeer) {
            return remotePeer->information.id == packetPeer.id;
        }
    );

    // if not already stored, create a new remote peer.
    if (itRemotePeer == context.remotePeers.end()) {
        // if not found, create a new peer
        const auto remotePeer = std::make_shared<RemotePeer>(fromAddress, fromAddressLength, packetPeer);
        // register it in the peer list
        context.remotePeers.push_back(remotePeer);
        // update the latest discovery time
        context.latestPeerDiscovery = std::chrono::high_resolution_clock::now();
    } else {
        // get the peer
        const auto& remotePeer = *itRemotePeer;
        // update the peer information
        remotePeer->update(packetPeer);
    }

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


}
