1
//! Account order of the pickers, from the shared `rpc::account_order` rules.
2

            
3
use std::cmp::Ordering;
4
use std::collections::HashMap;
5

            
6
use nomiscript::Value;
7
use rpc::account_order::{path_label, path_then_id};
8
use uuid::Uuid;
9

            
10
use super::row_id;
11
use crate::eval::plist_field_raw;
12

            
13
struct Node {
14
    name: Option<String>,
15
    parent: Option<Uuid>,
16
}
17

            
18
29495
fn uuid_field(element: &Value, key: &str) -> Option<Uuid> {
19
29495
    match plist_field_raw(element, key) {
20
29494
        Some(Value::String(text)) => Uuid::parse_str(&text).ok(),
21
1
        _ => None,
22
    }
23
29495
}
24

            
25
58990
fn account_id(element: &Value) -> Option<Uuid> {
26
58990
    row_id(element).and_then(|id| Uuid::parse_str(&id).ok())
27
58990
}
28

            
29
1960
fn nodes(elements: &[Value]) -> HashMap<Uuid, Node> {
30
1960
    elements
31
1960
        .iter()
32
29495
        .filter_map(|element| {
33
29495
            let name = match plist_field_raw(element, ":name") {
34
29495
                Some(Value::String(text)) => Some(text),
35
                _ => None,
36
            };
37
29495
            let parent = uuid_field(element, ":parent");
38
29495
            Some((account_id(element)?, Node { name, parent }))
39
29495
        })
40
        .collect()
41
1960
}
42

            
43
type Keyed = (Option<(String, Uuid)>, String, Value);
44

            
45
/// Records whose id is not a UUID go last, by their id text.
46
99903
fn compare(a: &Keyed, b: &Keyed) -> Ordering {
47
99903
    match (&a.0, &b.0) {
48
3976
        (Some((la, ia)), Some((lb, ib))) => path_then_id((la, *ia), (lb, *ib)),
49
3
        (Some(_), None) => Ordering::Less,
50
1
        (None, Some(_)) => Ordering::Greater,
51
95923
        (None, None) => a.1.cmp(&b.1),
52
    }
53
99903
}
54

            
55
/// Sort account records by path, then id, as `form-options` does.
56
1960
pub fn sort_by_path(elements: &mut [Value]) {
57
1960
    let nodes = nodes(elements);
58
1656
    let name_of = |id| nodes.get(&id).and_then(|node| node.name.as_deref());
59
1656
    let parent_of = |id| nodes.get(&id).and_then(|node| node.parent);
60
1960
    let mut keyed: Vec<Keyed> = elements
61
1960
        .iter()
62
29495
        .map(|element| {
63
29495
            let key = account_id(element).map(|id| (path_label(id, name_of, parent_of), id));
64
29495
            (key, row_id(element).unwrap_or_default(), element.clone())
65
29495
        })
66
        .collect();
67
1960
    keyed.sort_by(compare);
68
1960
    for (slot, (_, _, element)) in elements.iter_mut().zip(keyed) {
69
29495
        *slot = element;
70
    }
71
1960
}
72

            
73
#[cfg(test)]
74
mod tests;