use super::GEnclosure;
use glib::Boxed;
use news_flash::models::Enclosure;

#[derive(Clone, Debug, Default, Eq, Boxed)]
#[boxed_type(name = "NewsFlashGEnclosures")]
pub struct GEnclosures(Vec<GEnclosure>);

impl PartialEq for GEnclosures {
    fn eq(&self, other: &Self) -> bool {
        self.0
            .iter()
            .enumerate()
            .all(|(i, enclosure)| other.0.get(i).map(|other| enclosure.eq(other)).unwrap_or(false))
    }
}

impl From<Vec<Enclosure>> for GEnclosures {
    fn from(dt: Vec<Enclosure>) -> Self {
        Self(dt.into_iter().map(GEnclosure::from).collect())
    }
}

impl From<GEnclosures> for Vec<GEnclosure> {
    fn from(dt: GEnclosures) -> Self {
        dt.0
    }
}

impl<'a> From<&'a GEnclosures> for &'a [GEnclosure] {
    fn from(dt: &'a GEnclosures) -> Self {
        &dt.0
    }
}

impl AsRef<[GEnclosure]> for GEnclosures {
    fn as_ref(&self) -> &[GEnclosure] {
        &self.0
    }
}

impl AsMut<[GEnclosure]> for GEnclosures {
    fn as_mut(&mut self) -> &mut [GEnclosure] {
        &mut self.0
    }
}

impl GEnclosures {
    pub fn with_additional_data<S: AsRef<str>>(
        enclosures: Vec<Enclosure>,
        article_title: Option<S>,
        author: Option<S>,
        feed_title: Option<S>,
    ) -> Self {
        Self(
            enclosures
                .into_iter()
                .map(|e| {
                    GEnclosure::with_additional_data(
                        e,
                        article_title.as_ref().map(|s| s.as_ref().to_string()),
                        author.as_ref().map(|s| s.as_ref().to_string()),
                        feed_title.as_ref().map(|s| s.as_ref().to_string()),
                    )
                })
                .collect(),
        )
    }

    pub fn len(&self) -> usize {
        self.0.len()
    }

    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    pub fn push(&mut self, tag: GEnclosure) {
        self.0.push(tag);
    }

    pub fn remove(&mut self, index: usize) {
        self.0.remove(index);
    }
}
