use std::net::UdpSocket;

pub struct UdpSender {
    socket: UdpSocket,
    addr: String,
}

impl UdpSender {
    pub fn new(ip: &str, port: u16) -> Self {
        let socket = UdpSocket::bind("0.0.0.0:0")
            .expect("Impossible de créer le socket UDP");
        UdpSender {
            socket,
            addr: format!("{}:{}", ip, port),
        }
    }

    pub fn send(&self, json: &str) {
        let _ = self.socket.send_to(json.as_bytes(), &self.addr);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::net::UdpSocket;

    #[test]
    fn test_udp_envoi_loopback() {
        let recv = UdpSocket::bind("127.0.0.1:0").unwrap();
        let port = recv.local_addr().unwrap().port();
        recv.set_read_timeout(Some(std::time::Duration::from_millis(500))).unwrap();

        let sender = UdpSender::new("127.0.0.1", port);
        sender.send(r#"{"status":"ok"}"#);

        let mut buf = [0u8; 1024];
        let (n, _) = recv.recv_from(&mut buf).unwrap();
        let msg = std::str::from_utf8(&buf[..n]).unwrap();
        assert_eq!(msg, r#"{"status":"ok"}"#);
    }
}
