use itertools::process_results;
use serde::{Deserialize, Serialize};

use crate::{cache::Value, value::{FromValue, ToStringOrStringSet}};

#[derive(Eq, PartialEq, Serialize, Deserialize, Default)]
pub struct ValueSet<T>(Vec<T>)
where
    T: ToStringOrStringSet + Eq + PartialEq;

impl<T> From<Vec<T>> for ValueSet<T>
where
    T: ToStringOrStringSet + Eq + PartialEq,
{
    fn from(value: Vec<T>) -> Self {
        Self(value)
    }
}

impl<T> ValueSet<T>
where
    T: ToStringOrStringSet + Eq + PartialEq,
{
    pub fn iter(&self) -> impl Iterator<Item = &T> {
        self.0.iter()
    }

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

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

impl<T> IntoIterator for ValueSet<T>
where
    T: ToStringOrStringSet + Eq + PartialEq,
{
    type Item = T;

    type IntoIter = std::vec::IntoIter<T>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

impl<T> FromIterator<T> for ValueSet<T>
where
    T: ToStringOrStringSet + Eq + PartialEq,
{
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        Self(iter.into_iter().collect())
    }
}

impl<T> FromValue for ValueSet<T>
where
    T: FromValue + ToStringOrStringSet + Eq + PartialEq,
{
    fn from_value_opt(value: &crate::cache::Value) -> crate::ntds::Result<Option<Self>>
    where
        Self: Sized,
    {
        match value {
            Value::Multi(values) => {
                match process_results(values.iter().map(T::from_value_opt), |items| {
                    items.flatten().collect()
                }) {
                    Ok(values) => Ok(Some(values)),
                    Err(why) => {
                        log::error!(
                            "error while parsing values of type '{}': {why}",
                            std::any::type_name::<T>()
                        );
                        Err(why)
                    }
                }
            }
            value => Ok(Some(Self(T::from_value_opt(value)?.into_iter().collect()))),
        }
    }
}
