//! 打乱数组
use std::ops::Deref;

use rand::seq::SliceRandom;
/// 可打乱数组
#[derive(Debug)]
pub struct RandList<T>(Vec<T>);

impl<'a> From<&'a str> for RandList<&'a str> {
    fn from(s: &'a str) -> Self {
        Self(s.split("").filter(|&s| s != "").collect::<Vec<&str>>())
    }
}

impl<'a> From<&'a String> for RandList<&'a str> {
    fn from(s: &'a String) -> Self {
        Self(s.split("").filter(|&s| s != "").collect::<Vec<&str>>())
    }
}

impl<T> From<Vec<T>> for RandList<T> {
    fn from(v: Vec<T>) -> Self {
        Self(v)
    }
}

impl<T> Into<Vec<T>> for RandList<T> {
    fn into(self) -> Vec<T> {
        self.0
    }
}

impl<T> Deref for RandList<T> {
    type Target = Vec<T>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T> RandList<T> {
    /// 打乱内容
    pub fn shuffle(mut self) -> Self {
        let mut rng = rand::thread_rng();
        self.0.shuffle(&mut rng);
        self
    }
}

/// 找不到序号
#[derive(Debug)]
pub struct IndexNotFound;

impl<T: Eq> RandList<T> {
    /// 获得指定类型的序号
    pub fn get_index(&self, t: &T) -> Result<usize, IndexNotFound> {
        for (i, x) in self.0.iter().enumerate() {
            if x == t {
                return Ok(i);
            }
        }

        Err(IndexNotFound {})
    }
}
