//! Parameters for the [`Configuration::read_attribute`](crate::Configuration::read_attribute) command.

use le_stream::{FromLeStream, ToLeStream};
use num_traits::FromPrimitive;

use crate::Error;
use crate::ember::Status;
use crate::types::ByteSizedVec;

crate::frame::parameters::frame!(
    0x0108,
    { endpoint: u8, cluster: u16, attribute_id: u16, mask: u8, manufacturer_code: u16 },
    impl {
        impl Command {
            /// Creates command parameters.
            #[must_use]
            pub const fn new(
                endpoint: u8,
                cluster: u16,
                attribute_id: u16,
                mask: u8,
                manufacturer_code: u16,
            ) -> Self {
                Self {
                    endpoint,
                    cluster,
                    attribute_id,
                    mask,
                    manufacturer_code,
                }
            }
        }
    },
    { status: u8, payload: Attribute } => Configuration(configuration)::ReadAttribute,
    impl {
        /// Converts the response into an [`Attribute`] or an appropriate [`Error`] depending on its status.
        impl TryFrom<Response> for Attribute {
            type Error = Error;

            fn try_from(response: Response) -> Result<Self, Self::Error> {
                match Status::from_u8(response.status).ok_or(response.status) {
                    Ok(Status::Success) => Ok(response.payload),
                    other => Err(other.into()),
                }
            }
        }
    }
);

/// Read attribute data.
#[derive(Clone, Debug, Eq, PartialEq, FromLeStream, ToLeStream)]
pub struct Attribute {
    data_type: u8,
    data: ByteSizedVec<u8>,
}

impl Attribute {
    /// Attribute data type.
    #[must_use]
    pub const fn data_type(&self) -> u8 {
        self.data_type
    }

    /// Attribute data.
    #[must_use]
    pub fn data(&self) -> &[u8] {
        self.data.as_ref()
    }
}
