/**
 * @file udp_sender.cpp
 * @brief UDP 发送器实现
 */

#include "udp_sender.h"
#include "../utils/logger.h"

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>

UDPSender::UDPSender(const std::string& host, int port)
    : m_host(host), m_port(port), m_socket_fd(-1), m_sockaddr(nullptr) {
    
    // 创建 UDP socket
    m_socket_fd = socket(AF_INET, SOCK_DGRAM, 0);
    if (m_socket_fd < 0) {
        LOG_ERROR("[UDP] Failed to create socket");
        return;
    }
    
    // 配置目标地址
    struct sockaddr_in* addr = new struct sockaddr_in;
    memset(addr, 0, sizeof(*addr));
    addr->sin_family = AF_INET;
    addr->sin_port = htons(m_port);
    
    if (inet_pton(AF_INET, m_host.c_str(), &addr->sin_addr) <= 0) {
        LOG_ERROR("[UDP] Invalid address: %s", m_host.c_str());
        close(m_socket_fd);
        m_socket_fd = -1;
        delete addr;
        return;
    }
    
    m_sockaddr = addr;
    
    LOG_INFO("[UDP] Initialized to %s:%d", m_host.c_str(), m_port);
}

UDPSender::~UDPSender() {
    if (m_socket_fd >= 0) {
        close(m_socket_fd);
    }
    
    if (m_sockaddr) {
        delete (struct sockaddr_in*)m_sockaddr;
    }
}

int UDPSender::send(const void* data, size_t size) {
    if (m_socket_fd < 0 || !m_sockaddr) {
        return -1;
    }
    
    struct sockaddr_in* addr = (struct sockaddr_in*)m_sockaddr;
    
    ssize_t sent = sendto(m_socket_fd, data, size, 0,
                          (struct sockaddr*)addr, sizeof(*addr));
    
    if (sent < 0) {
        LOG_ERROR("[UDP] Send failed");
        return -1;
    }
    
    return (int)sent;
}
