#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ImuBaroPayload {
    pub timestamp: u32,
    pub altitude: f32,
    pub pressure: f32,
    pub temperature: f32,
}

impl ImuBaroPayload {
    pub const SYSTEM_ID: u8 = 1;
    pub const MODULE_ID: u8 = 4;
    pub const LEN: usize = 16;

    pub fn validate_payload(payload: &[u8]) -> Result<(), crate::gen::payload_io::PayloadError> {
        if payload.len() != Self::LEN {
            return Err(crate::gen::payload_io::PayloadError::LengthMismatch { expected: Self::LEN, actual: payload.len() });
        }
        Ok(())
    }

    pub fn parse(payload: &[u8]) -> Result<ImuBaroPayload, crate::gen::payload_io::PayloadError> {
        Self::validate_payload(payload)?;
        let mut cursor = crate::gen::payload_io::PayloadCursor::new(payload);
        Ok(Self {
            timestamp: cursor.read_u32(),
            altitude: cursor.read_f32(),
            pressure: cursor.read_f32(),
            temperature: cursor.read_f32(),
        })
    }

    pub fn from_bytes_exact(payload: &[u8; Self::LEN]) -> ImuBaroPayload {
        // Length already guaranteed by the array type
        Self::parse(payload).expect("slice length matches payload size")
    }

    pub fn to_bytes(&self) -> [u8; Self::LEN] {
        let mut buf = [0u8; Self::LEN];
        let mut writer = crate::gen::payload_io::PayloadWriter::new(&mut buf);
        writer.write_u32(self.timestamp);
        writer.write_f32(self.altitude);
        writer.write_f32(self.pressure);
        writer.write_f32(self.temperature);
        buf
    }
}
