#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,
    std::vector<std::uint8_t>& data,
    const sockaddr_storage& fromAddress,
    const socklen_t fromAddressLength
) {
    packet::base::Packet packet {};
    packet::base::PacketContent packetContent {};

    // create the packet header (available to read for everyone)
    packet.channel = 0;

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

    packetContent.eventType = EventType::INFO;
    packetContent.data = packetData.serialize();

    packet.setContent(context, packet::base::SecurityMode::PLAIN, packetContent);

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

    const auto serializedPacket = packet.serialize();

    // send back our information
    if (sendto(
        context.socket,
        serializedPacket.data(),
        serializedPacket.size(),
        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;
}



}
