#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct GnssConfigPayload {
    pub meas_rate: u16,
    pub update_rate: u16,
    pub use_nmea: u8,
    pub use_ubx: u8,
    pub use_rtcm: u8,
    pub rsvd_1: u8,
    pub rsvd_2: u16,
    pub rsvd_3: u16,
    pub rsvd_4: u16,
    pub rsvd_5: u16,
    pub baud_rate: u32,
}

impl GnssConfigPayload {
    pub const SYSTEM_ID: u8 = 2;
    pub const MODULE_ID: u8 = 0;
    pub const LEN: usize = 20;

    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<GnssConfigPayload, crate::gen::payload_io::PayloadError> {
        Self::validate_payload(payload)?;
        let mut cursor = crate::gen::payload_io::PayloadCursor::new(payload);
        Ok(Self {
            meas_rate: cursor.read_u16(),
            update_rate: cursor.read_u16(),
            use_nmea: cursor.read_u8(),
            use_ubx: cursor.read_u8(),
            use_rtcm: cursor.read_u8(),
            rsvd_1: cursor.read_u8(),
            rsvd_2: cursor.read_u16(),
            rsvd_3: cursor.read_u16(),
            rsvd_4: cursor.read_u16(),
            rsvd_5: cursor.read_u16(),
            baud_rate: cursor.read_u32(),
        })
    }

    pub fn from_bytes_exact(payload: &[u8; Self::LEN]) -> GnssConfigPayload {
        // 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_u16(self.meas_rate);
        writer.write_u16(self.update_rate);
        writer.write_u8(self.use_nmea);
        writer.write_u8(self.use_ubx);
        writer.write_u8(self.use_rtcm);
        writer.write_u8(self.rsvd_1);
        writer.write_u16(self.rsvd_2);
        writer.write_u16(self.rsvd_3);
        writer.write_u16(self.rsvd_4);
        writer.write_u16(self.rsvd_5);
        writer.write_u32(self.baud_rate);
        buf
    }
}
