use super::{Choice, Model, Pick};
pub(crate) const JOINER: char = '@';
pub(crate) const SERVER: &str = "server";
pub(crate) fn split(name: &str) -> (&str, Option<&str>) {
match name.rsplit_once(JOINER) {
Some((row, client)) if !row.is_empty() && !client.is_empty() => (row, Some(client)),
_ => (name, None),
}
}
pub(crate) fn of(name: &str) -> Option<&str> {
split(name).1
}
pub(crate) fn row(name: &str) -> &str {
split(name).0
}
pub(crate) fn word(machine: Option<&str>) -> &str {
machine.unwrap_or(SERVER)
}
impl Model {
fn provider_names(&self) -> Vec<String> {
let mut names: Vec<String> = self
.providers
.iter()
.flatten()
.map(|row| row.name.clone())
.collect();
if let Some(worker) = self.worker()
&& !names.contains(&worker.provider)
{
names.insert(0, worker.provider.clone());
}
names
}
pub(super) fn machine_rows(&self) -> Vec<Choice> {
let at = self.worker().map(|w| of(&w.provider).map(str::to_owned));
let mut machines: Vec<Option<String>> = vec![None];
for name in self.provider_names() {
let machine = of(&name).map(str::to_owned);
if !machines.contains(&machine) {
machines.push(machine);
}
}
machines
.into_iter()
.map(|machine| Choice {
text: word(machine.as_deref()).to_owned(),
current: at.as_ref() == Some(&machine),
pick: Pick::Machine(machine),
})
.collect()
}
pub(super) fn provider_rows(&self, machine: Option<&str>) -> Vec<Choice> {
let worker = self.worker().map(|w| w.provider.as_str());
self.provider_names()
.into_iter()
.filter(|name| of(name) == machine)
.map(|name| Choice {
current: worker == Some(name.as_str()),
text: row(&name).to_owned(),
pick: Pick::Provider(name),
})
.collect()
}
}
#[cfg(test)]
mod tests;