use core::fmt::{self, Display};

use le_stream::{FromLeStream, ToLeStream};

use super::LowByte;

/// Legacy EZSP header.
///
/// The legacy format stores the sequence number, one frame-control byte, and an
/// 8-bit frame ID. It is required for the initial `version` command and for
/// protocol versions before 8.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, FromLeStream, ToLeStream)]
pub struct Legacy {
    sequence: u8,
    low_byte: LowByte,
    id: u8,
}

impl Legacy {
    /// Creates a new legacy EZSP header.
    #[must_use]
    pub const fn new(sequence: u8, low_byte: LowByte, id: u8) -> Self {
        Self {
            sequence,
            low_byte,
            id,
        }
    }

    /// Returns the sequence number.
    #[must_use]
    pub const fn sequence(self) -> u8 {
        self.sequence
    }

    /// Returns the low byte.
    #[must_use]
    pub const fn low_byte(self) -> LowByte {
        self.low_byte
    }

    /// Returns the ID.
    #[must_use]
    pub const fn id(self) -> u8 {
        self.id
    }
}

impl Display for Legacy {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "Legacy {{ sequence: {:#04X}, low_byte: {}, id: {:#04X}}}",
            self.sequence, self.low_byte, self.id
        )
    }
}
