//! Network jitter measurement

use std::time::Duration;

use super::super::error::ProfilingError;
use super::iperf::{IperfClient, IperfConfig};
use super::protocol::Protocol;

/// Network jitter measurement result
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct JitterResult {
    pub server: String,
    pub jitter_ms: f64,
    pub min_latency_ms: f64,
    pub max_latency_ms: f64,
}

impl Default for JitterResult {
    fn default() -> Self {
        Self {
            server: "unknown".to_string(),
            jitter_ms: 0.0,
            min_latency_ms: 0.0,
            max_latency_ms: 0.0,
        }
    }
}

/// Measure network jitter using UDP mode
pub fn run_jitter_test(server: &str) -> Result<JitterResult, ProfilingError> {
    super::super::logging::log_info(&format!("Measuring jitter to {}", server));

    let client = IperfClient::new(server)?;

    let config = IperfConfig::new()
        .with_server(server)
        .with_duration(Duration::from_secs(10))
        .with_protocol(Protocol::Udp)
        .with_bandwidth_limit(10_000_000); // 10 Mbps

    let result = client.run_iperf_test(&config)?;

    let jitter_ms = result.jitter_ms.unwrap_or(0.0);

    Ok(JitterResult {
        server: server.to_string(),
        jitter_ms,
        min_latency_ms: 0.0,
        max_latency_ms: 0.0,
    })
}
