use std::fmt;
use chrono::{DateTime, Utc};
use uuid::Uuid;
use crate::utils::{flatten_str, flatten_variable_name};
#[derive(Clone, PartialEq, Eq)]
#[cfg_attr(test, derive(Debug))]
pub struct VariableCompletion {
pub id: Uuid,
pub source: String,
pub root_cmd: String,
pub flat_root_cmd: String,
pub variable: String,
pub flat_variable: String,
pub suggestions_provider: String,
pub created_at: DateTime<Utc>,
pub updated_at: Option<DateTime<Utc>>,
}
impl VariableCompletion {
pub fn new(
source: impl Into<String>,
root_cmd: impl AsRef<str>,
variable_name: impl AsRef<str>,
suggestions_provider: impl Into<String>,
) -> Self {
let root_cmd = root_cmd.as_ref().trim().to_string();
let variable = variable_name.as_ref().trim().to_string();
Self {
id: Uuid::now_v7(),
source: source.into(),
flat_root_cmd: flatten_str(&root_cmd),
root_cmd,
flat_variable: flatten_variable_name(&variable),
variable,
suggestions_provider: suggestions_provider.into(),
created_at: Utc::now(),
updated_at: None,
}
}
pub fn with_root_cmd(mut self, root_cmd: impl AsRef<str>) -> Self {
self.root_cmd = root_cmd.as_ref().trim().to_string();
self.flat_root_cmd = flatten_str(&self.root_cmd);
self
}
pub fn with_variable(mut self, variable_name: impl AsRef<str>) -> Self {
self.variable = variable_name.as_ref().trim().to_string();
self.flat_variable = flatten_variable_name(&self.variable);
self
}
pub fn with_suggestions_provider(mut self, suggestions_provider: impl Into<String>) -> Self {
self.suggestions_provider = suggestions_provider.into();
self
}
pub fn is_global(&self) -> bool {
self.flat_root_cmd.is_empty()
}
}
impl fmt::Display for VariableCompletion {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.is_global() {
write!(f, "$ {}: {}", self.variable, self.suggestions_provider)
} else {
write!(
f,
"$ ({}) {}: {}",
self.root_cmd, self.variable, self.suggestions_provider
)
}
}
}