use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use serde_json::{Value, json};
use crate::settings::{self, Settings};
use crate::ui::{Aim, Servers, Tab};
const FILE: &str = "place.json";
const AIM: &str = "aim";
const CHANNEL: &str = "channel";
const ADDRESS: &str = "address";
const OPEN: &str = "open";
const OPENED: &str = "opened";
const AIMED: &str = "aimed";
const PINNED: &str = "pinned";
const KEPT: &str = "kept";
const ROOT_ID: &str = "root_id";
const SETTINGS: &str = "settings";
const RETIRED_OWN: &str = "(this box's own engine)";
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Place {
pub aim: Option<Aim>,
pub servers: Servers,
pub pinned: bool,
pub kept: Vec<Tab>,
pub settings: Settings,
}
impl Place {
pub fn of(model: &crate::ui::Model) -> Self {
Self {
aim: model.aim.clone(),
servers: model.servers.clone(),
pinned: model.bar.pinned,
kept: model.bar.kept.clone(),
settings: model.settings.clone(),
}
}
}
pub fn at(root: &Path) -> PathBuf {
root.join(FILE)
}
pub fn read(root: &Path) -> Place {
let held = std::fs::read_to_string(at(root))
.ok()
.and_then(|text| serde_json::from_str::<Value>(&text).ok())
.unwrap_or(Value::Null);
Place {
aim: aimed(&held),
servers: Servers {
open: held.get(OPEN).and_then(Value::as_str).map(current),
opened: table(&held, OPENED, Value::as_u64),
aimed: table(&held, AIMED, |held| held.as_str().map(str::to_owned)),
..Servers::default()
},
pinned: held.get(PINNED).and_then(Value::as_bool).unwrap_or(false),
kept: kept(&held),
settings: settings::from_json(held.get(SETTINGS).unwrap_or(&Value::Null)),
}
}
fn kept(held: &Value) -> Vec<Tab> {
held.get(KEPT)
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(|entry| {
Some(Tab {
aim: aim_in(entry)?,
root_id: entry.get(ROOT_ID)?.as_str()?.to_owned(),
})
})
.collect()
}
fn aimed(held: &Value) -> Option<Aim> {
aim_in(held.get(AIM)?)
}
fn aim_in(held: &Value) -> Option<Aim> {
let text = |key| held.get(key)?.as_str().map(str::to_owned);
Some(Aim {
channel: current(&text(CHANNEL)?),
address: text(ADDRESS)?,
})
}
fn current(name: &str) -> String {
if name == RETIRED_OWN {
crate::seat::OWN
} else {
name
}
.to_owned()
}
fn table<T>(held: &Value, key: &str, read: impl Fn(&Value) -> Option<T>) -> BTreeMap<String, T> {
held.get(key)
.and_then(Value::as_object)
.map(|rows| {
rows.iter()
.filter_map(|(name, held)| Some((current(name), read(held)?)))
.collect()
})
.unwrap_or_default()
}
pub fn write(root: &Path, place: &Place) -> Result<(), String> {
let mut body = json!({
AIM: place
.aim
.clone()
.map(|aim| json!({ CHANNEL: aim.channel, ADDRESS: aim.address })),
OPEN: place.servers.open,
OPENED: place.servers.opened,
AIMED: place.servers.aimed,
PINNED: place.pinned,
KEPT: place
.kept
.iter()
.map(|tab| json!({ CHANNEL: tab.aim.channel, ADDRESS: tab.aim.address, ROOT_ID: tab.root_id }))
.collect::<Vec<_>>(),
});
let knobs = settings::to_json(&place.settings);
if let Some(keys) = body.as_object_mut().filter(|_| knobs != json!({})) {
keys.insert(SETTINGS.to_owned(), knobs);
}
std::fs::create_dir_all(root).map_err(|e| format!("{}: {e}", root.display()))?;
std::fs::write(at(root), body.to_string()).map_err(|e| format!("{}: {e}", at(root).display()))
}
#[cfg(test)]
mod tests;