#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct OperatingConfigPayload {
    pub fsm_state: u8,
    pub fsm_prev_state: u8,
    pub fsm_command: u8,
    pub msg_uart_rate_divider: u8,
    pub rsvd_2: u16,
    pub rsvd_3: u16,
    pub rsvd_4: u16,
    pub rsvd_5: u16,
    pub rsvd_6: u16,
    pub rsvd_7: u16,
    pub version: u32,
    pub status: u32,
    pub msg_uart_baud_rate: u32,
}

impl OperatingConfigPayload {
    pub const SYSTEM_ID: u8 = 0;
    pub const MODULE_ID: u8 = 0;
    pub const LEN: usize = 28;

    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<OperatingConfigPayload, crate::gen::payload_io::PayloadError> {
        Self::validate_payload(payload)?;
        let mut cursor = crate::gen::payload_io::PayloadCursor::new(payload);
        Ok(Self {
            fsm_state: cursor.read_u8(),
            fsm_prev_state: cursor.read_u8(),
            fsm_command: cursor.read_u8(),
            msg_uart_rate_divider: cursor.read_u8(),
            rsvd_2: cursor.read_u16(),
            rsvd_3: cursor.read_u16(),
            rsvd_4: cursor.read_u16(),
            rsvd_5: cursor.read_u16(),
            rsvd_6: cursor.read_u16(),
            rsvd_7: cursor.read_u16(),
            version: cursor.read_u32(),
            status: cursor.read_u32(),
            msg_uart_baud_rate: cursor.read_u32(),
        })
    }

    pub fn from_bytes_exact(payload: &[u8; Self::LEN]) -> OperatingConfigPayload {
        // 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_u8(self.fsm_state);
        writer.write_u8(self.fsm_prev_state);
        writer.write_u8(self.fsm_command);
        writer.write_u8(self.msg_uart_rate_divider);
        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_u16(self.rsvd_6);
        writer.write_u16(self.rsvd_7);
        writer.write_u32(self.version);
        writer.write_u32(self.status);
        writer.write_u32(self.msg_uart_baud_rate);
        buf
    }
}
