
use std::time::SystemTime;

#[derive(Debug, Clone, Default)]
pub struct MailboxStatistics {

    pub total_sent: u64,

    pub total_received: u64,

    pub total_timeout: u64,

    pub total_mailbox_error: u64,

    pub total_protocol_error: u64,

    pub total_cancelled: u64,

    pub last_error_code: u32,

    pub last_error_time: Option<SystemTime>,

    pub average_latency_us: f64,
}

impl MailboxStatistics {

    pub fn empty() -> Self { Self::default() }
}

pub(crate) use crate::utils::ffi::EcMbxStatsC;

impl From<EcMbxStatsC> for MailboxStatistics {
    fn from(c: EcMbxStatsC) -> Self {
        let avg = if c.total_received > 0 {
            c.total_latency_us as f64 / c.total_received as f64
        } else {
            0.0
        };

        let last_err_time = if c.last_error_time_us > 0 {
            use std::time::{Duration, UNIX_EPOCH};
            Some(UNIX_EPOCH + Duration::from_micros(c.last_error_time_us))
        } else {
            None
        };

        Self {
            total_sent: c.total_sent,
            total_received: c.total_received,
            total_timeout: c.total_timeout,
            total_mailbox_error: c.total_mbx_error,
            total_protocol_error: c.total_proto_error,
            total_cancelled: c.total_cancelled,
            last_error_code: c.last_error_code,
            last_error_time: last_err_time,
            average_latency_us: avg,
        }
    }
}
