#include "SearchEvent.hpp"

#include <cerrno>
#include <sys/socket.h>
#include <cstring>
#include <iostream>
#include <ostream>

#include "packets/base/SecurityMode.hpp"
#include "packets/info/InfoPacketData.hpp"


namespace drp {


void event::SearchEvent::handle(
    Context& context,
    const packet::base::PacketContent& content,
    const sockaddr_storage& fromAddress,
    const socklen_t fromAddressLength
) {
    packet::base::Packet packet {};

    // create the packet header (available to read for everyone)
    packet.channel = 0;
    packet.securityMode = static_cast<std::uint8_t>(packet::base::SecurityMode::PLAIN);

    // create the packet data containing our information
    packet::info::InfoPacketData packetData {};
    packetData.peer = context.me;

    packet.setContent(packetData.toGeneric());

    // TODO(Faraphel): send back the timestamp too

    // send back our information
    if (sendto(
        context.socket,
        &packet,
        sizeof(packet),
        0,
        reinterpret_cast<const sockaddr*>(&fromAddress),
        fromAddressLength
    ) == -1) {
        std::cerr << "[Event - Search] Could not send information: " << strerror(errno) << std::endl;
        return;
    }

    std::cout << "[Event - Search] Sent back information." << std::endl;
}



}
