//! Service Identifier Descriptor — ETSI TS 102 809 §7.2, Table 39 (tag 0x71).
//!
//! Carried in the SDT/service loop to give a service a stable textual
//! identifier. The body is a run of `textual_service_identifier_bytes`
//! (ASCII), per ts_102_809_apps.md "Table 39 — Service identifier descriptor"
//! (PDF p. 62).

use super::descriptor_body;
use crate::error::{Error, Result};
use crate::text::DvbText;
use dvb_common::{Parse, Serialize};

/// Descriptor tag for service_identifier_descriptor.
pub const TAG: u8 = 0x71;
const HEADER_LEN: usize = 2;

/// Service Identifier Descriptor.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
pub struct ServiceIdentifierDescriptor<'a> {
    /// Textual service identifier (ASCII per TS 102 809 Table 39).
    pub textual_service_identifier: DvbText<'a>,
}

impl<'a> Parse<'a> for ServiceIdentifierDescriptor<'a> {
    type Error = crate::error::Error;
    fn parse(bytes: &'a [u8]) -> Result<Self> {
        let body = descriptor_body(
            bytes,
            TAG,
            "ServiceIdentifierDescriptor",
            "unexpected tag for service_identifier_descriptor",
        )?;
        Ok(Self {
            textual_service_identifier: DvbText::new(body),
        })
    }
}

impl Serialize for ServiceIdentifierDescriptor<'_> {
    type Error = crate::error::Error;
    fn serialized_len(&self) -> usize {
        HEADER_LEN + self.textual_service_identifier.raw().len()
    }

    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        if self.textual_service_identifier.raw().len() > u8::MAX as usize {
            return Err(Error::InvalidDescriptor {
                tag: TAG,
                reason: "textual_service_identifier exceeds 255 bytes",
            });
        }
        let len = self.serialized_len();
        if buf.len() < len {
            return Err(Error::OutputBufferTooSmall {
                need: len,
                have: buf.len(),
            });
        }
        buf[0] = TAG;
        buf[1] = self.textual_service_identifier.raw().len() as u8;
        buf[HEADER_LEN..len].copy_from_slice(self.textual_service_identifier.raw());
        Ok(len)
    }
}
impl<'a> crate::traits::DescriptorDef<'a> for ServiceIdentifierDescriptor<'a> {
    const TAG: u8 = TAG;
    const NAME: &'static str = "SERVICE_IDENTIFIER";
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_extracts_identifier_text() {
        let bytes = [TAG, 6, b'B', b'B', b'C', b'O', b'N', b'E'];
        let d = ServiceIdentifierDescriptor::parse(&bytes).unwrap();
        assert_eq!(d.textual_service_identifier.raw(), b"BBCONE");
        assert_eq!(d.textual_service_identifier.decode(), "BBCONE");
    }

    #[test]
    fn parse_rejects_wrong_tag() {
        assert!(matches!(
            ServiceIdentifierDescriptor::parse(&[0x70, 1, 0]).unwrap_err(),
            Error::InvalidDescriptor { tag: 0x70, .. }
        ));
    }

    #[test]
    fn parse_rejects_short_header() {
        assert!(matches!(
            ServiceIdentifierDescriptor::parse(&[TAG]).unwrap_err(),
            Error::BufferTooShort { .. }
        ));
    }

    #[test]
    fn parse_rejects_length_overrunning_buffer() {
        let bytes = [TAG, 5, 1, 2, 3];
        assert!(matches!(
            ServiceIdentifierDescriptor::parse(&bytes).unwrap_err(),
            Error::BufferTooShort { .. }
        ));
    }

    #[test]
    fn empty_identifier_is_valid() {
        let bytes = [TAG, 0];
        let d = ServiceIdentifierDescriptor::parse(&bytes).unwrap();
        assert!(d.textual_service_identifier.raw().is_empty());
    }

    #[test]
    fn serialize_round_trip() {
        let d = ServiceIdentifierDescriptor {
            textual_service_identifier: DvbText::new(b"CH4-HD"),
        };
        let mut buf = vec![0u8; d.serialized_len()];
        d.serialize_into(&mut buf).unwrap();
        assert_eq!(ServiceIdentifierDescriptor::parse(&buf).unwrap(), d);
    }

    #[test]
    fn serialize_rejects_too_small_buffer() {
        let d = ServiceIdentifierDescriptor {
            textual_service_identifier: DvbText::new(b"test"),
        };
        let mut buf = vec![0u8; 1];
        assert!(matches!(
            d.serialize_into(&mut buf).unwrap_err(),
            Error::OutputBufferTooSmall { .. }
        ));
    }

    #[cfg(feature = "serde")]
    #[test]
    fn serde_serializes_to_stable_json() {
        let d = ServiceIdentifierDescriptor {
            textual_service_identifier: DvbText::new(b"ITV1"),
        };
        let j = serde_json::to_string(&d).unwrap();
        let _v: serde_json::Value = serde_json::from_str(&j).unwrap();
        assert!(j.contains("textual_service_identifier"));
    }
}
