use serde_json::{json, Value};
pub fn require_v2(raw: &Value) -> Result<u64, &'static str> {
match raw.get("v").and_then(|v| v.as_u64()) {
Some(2) => Ok(2),
Some(_) => Err("unsupported protocol version"),
None => Err("missing v"),
}
}
pub fn stamp_id_if_missing(raw: &mut Value) {
if raw.get("id").map_or(true, |x| x.is_null()) {
raw["id"] = json!(ulid::Ulid::new().to_string());
}
}
pub fn stamp_ts_if_missing(raw: &mut Value) {
if raw.get("ts").is_none() {
raw["ts"] = json!(chrono::Utc::now().to_rfc3339());
}
}
pub fn default_target_if_null(raw: &mut Value) {
if raw.get("target").map_or(false, |x| x.is_null()) {
raw["target"] = json!({
"id": null,
"selector": null,
"rect": {"x": 0.0, "y": 0.0, "w": 0.0, "h": 0.0}
});
}
}
pub fn default_rect_if_null(raw: &mut Value) {
if let Some(t) = raw.get_mut("target") {
if t.get("rect").map_or(false, |r| r.is_null()) {
t["rect"] = json!({"x": 0.0, "y": 0.0, "w": 0.0, "h": 0.0});
}
}
}
pub fn apply_all(raw: &mut Value) {
stamp_id_if_missing(raw);
stamp_ts_if_missing(raw);
default_target_if_null(raw);
default_rect_if_null(raw);
}