use inquire::autocompletion::{Autocomplete, Replacement};

const TRIGGER: &str = "cd ";

#[derive(Clone)]
/// Defines a `StringListAutoCompleter`.
pub struct StringListAutoCompleter {
    string_list: Vec<String>,
}

/// Methods for `StringListAutoCompleter`.
impl StringListAutoCompleter {
    pub fn new(string_list: Vec<String>) -> Self {
        Self { string_list }
    }
}

/// Impl `Autocomplete` for `StringListAutoCompleter`.
impl Autocomplete for StringListAutoCompleter {
    fn get_suggestions(&mut self, _input: &str) -> Result<Vec<String>, inquire::CustomUserError> {
        Ok(vec![])
    }

    fn get_completion(
        &mut self,
        input: &str,
        _highlighted_suggestion: Option<String>,
    ) -> Result<Replacement, inquire::CustomUserError> {
        let Some(filter) = input.strip_prefix(TRIGGER) else {
            return Ok(Replacement::None);
        };

        let filter_lower = filter.to_lowercase();

        let matched: Vec<_> = self
            .string_list
            .iter()
            .filter(|entry| entry.to_lowercase().starts_with(&filter_lower))
            .collect();

        Ok(if matched.len() == 1 {
            Replacement::Some(format!("{TRIGGER}{}", matched[0]))
        } else {
            Replacement::None
        })
    }
}
