#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ImuAccPayload {
    pub timestamp: u32,
    pub x: f32,
    pub y: f32,
    pub z: f32,
    pub uncomp_x: f32,
    pub uncomp_y: f32,
    pub uncomp_z: f32,
    pub cal_b_x: f32,
    pub cal_b_y: f32,
    pub cal_b_z: f32,
}

impl ImuAccPayload {
    pub const SYSTEM_ID: u8 = 1;
    pub const MODULE_ID: u8 = 1;
    pub const LEN: usize = 40;

    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<ImuAccPayload, 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(),
            x: cursor.read_f32(),
            y: cursor.read_f32(),
            z: cursor.read_f32(),
            uncomp_x: cursor.read_f32(),
            uncomp_y: cursor.read_f32(),
            uncomp_z: cursor.read_f32(),
            cal_b_x: cursor.read_f32(),
            cal_b_y: cursor.read_f32(),
            cal_b_z: cursor.read_f32(),
        })
    }

    pub fn from_bytes_exact(payload: &[u8; Self::LEN]) -> ImuAccPayload {
        // 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.x);
        writer.write_f32(self.y);
        writer.write_f32(self.z);
        writer.write_f32(self.uncomp_x);
        writer.write_f32(self.uncomp_y);
        writer.write_f32(self.uncomp_z);
        writer.write_f32(self.cal_b_x);
        writer.write_f32(self.cal_b_y);
        writer.write_f32(self.cal_b_z);
        buf
    }
}
