use serde::{Deserialize, Serialize};

/// This type specifies the offset of the client's subnet in
/// seconds from Coordinated Universal Time (UTC) through an `i32`.
///
/// The offset is expressed as a two's complement 32-bit integer.
/// A positive offset indicates a location east of the zero meridian.
/// A negative offset indicates a location west of the zero meridian.
#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
pub struct TimeOffset(i32);

impl TimeOffset {
    /// Create a `TimeOffset`.
    pub fn new(seconds: i32) -> Self {
        Self(seconds)
    }

    /// Used, when serializing, to add to the byte buffer.
    #[inline]
    pub fn extend_into(&self, bytes: &mut Vec<u8>, tag: u8) {
        bytes.push(tag); // tag
        bytes.push(4); // length
        bytes.extend_from_slice(&self.0.to_be_bytes()); // value
    }
}

impl From<&[u8]> for TimeOffset {
    fn from(value: &[u8]) -> Self {
        let bytes: [u8; 4] = value.try_into().unwrap();
        Self(i32::from_be_bytes(bytes))
    }
}
