// This file was generated by x-IMU3-API/Rust/src/data_messages/generate_data_messages.py

use crate::data_messages::*;
use crate::receive_error::*;
use std::fmt;
use std::mem::size_of;

#[repr(C)]
#[derive(Clone, Copy)]
pub struct LinearAccelerationMessage {
    pub timestamp: u64,
    pub x: f32,
    pub y: f32,
    pub z: f32,
}

impl Default for LinearAccelerationMessage {
    fn default() -> Self {
        Self {
            timestamp: 0,
            x: 0.0,
            y: 0.0,
            z: 0.0,
        }
    }
}

impl DataMessage for LinearAccelerationMessage {
    fn get_ascii_id() -> u8 {
        b'L'
    }

    fn parse_ascii(message: &str) -> Result<Self, ReceiveError> {
        match scan_fmt!(message, "{},{d},{f},{f},{f}\n", char, u64, f32, f32, f32) {
            Ok((_, timestamp, x, y, z)) => Ok(Self {
                timestamp,
                x,
                y,
                z,
            }),
            Err(_) => Err(ReceiveError::UnableToParseAsciiMessage),
        }
    }

    fn parse_binary(message: &[u8]) -> Result<Self, ReceiveError> {
        #[repr(C, packed)]
        struct BinaryMessage {
            _id: u8,
            timestamp: u64,
            x: f32,
            y: f32,
            z: f32,
            _termination: u8,
        }

        if message.len() != size_of::<BinaryMessage>() {
            return Err(ReceiveError::InvalidBinaryMessageLength);
        }

        let binary_message = unsafe {
            let ref binary_message = *(message.as_ptr() as *const BinaryMessage);
            binary_message
        };

        Ok(Self {
            timestamp: binary_message.timestamp,
            x: binary_message.x,
            y: binary_message.y,
            z: binary_message.z,
        })
    }

    fn get_csv_file_name(&self) -> &'static str {
        "LinearAcceleration.csv"
    }

    fn get_csv_headings(&self) -> &'static str {
        "Timestamp (us),X (g),Y (g),Z (g)\n"
    }

    fn to_csv_row(&self) -> String {
        format!("{},{:.6},{:.6},{:.6}\n", self.timestamp, self.x, self.y, self.z)
    }
}

impl fmt::Display for LinearAccelerationMessage {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(formatter, "{:>8} us {:>8.3} g {:>8.3} g {:>8.3} g", self.timestamp, self.x, self.y, self.z)
    }
}