1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
use std::{cmp::max, collections::HashMap, fmt::Display};

use anyhow::Result;

#[derive(PartialEq, Eq)]
enum Value {
    Seperator,
    NewLine,
    Entry(String, String),
}

/// Simple helper to print key-value entries where the keys are all alligned.
///
/// Here is an example of how it looks:
///
/// --------------------------------------------------------------------------
/// account 0: fuel12sdaglkadsgmoaeigm49309k403ydxtqmzuaqtzdjlsww5t2jmg9skutn8n
/// Asset ID : 0000000000000000000000000000000000000000000000000000000000000000
/// Amount   : 499999800
///
/// Asset ID : 0000000000000000000000000000000000000000000000000000000000000001
/// Amount   : 359989610
/// --------------------------------------------------------------------------
/// account 1: fuel29asdfjoiajg934344iw9e8jfasoiaeigjaergokjaeoigjaeg9ij39ijg34
/// Asset ID : 0000000000000000000000000000000000000000000000000000000000000000
/// Amount   : 268983615
#[derive(Default)]
pub struct List(Vec<Value>);

impl List {
    pub fn add(&mut self, title: impl ToString, value: impl ToString) {
        self.0
            .push(Value::Entry(title.to_string(), value.to_string()));
    }

    pub fn add_newline(&mut self) {
        self.0.push(Value::NewLine);
    }

    pub fn add_seperator(&mut self) {
        if self.0.last() == Some(&Value::Seperator) {
            return;
        }
        self.0.push(Value::Seperator);
    }

    pub fn longest_title(&self) -> usize {
        self.0
            .iter()
            .map(|value| match value {
                Value::Seperator => 0,
                Value::NewLine => 0,
                Value::Entry(title, _) => title.len(),
            })
            .max()
            .unwrap_or(0)
    }
}

impl Display for List {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let longest_key = self.longest_title();
        let entries = self
            .0
            .iter()
            .map(|entry| match entry {
                Value::Seperator => None,
                Value::NewLine => Some("".to_owned()),
                Value::Entry(title, value) => {
                    let padding = " ".repeat(longest_key - title.len());
                    Some(format!("{}{}: {}", title, padding, value))
                }
            })
            .collect::<Vec<_>>();

        let longest_entry = entries
            .iter()
            .map(|entry| entry.as_ref().map(|s| s.len()).unwrap_or(0))
            .max()
            .unwrap_or(0);

        let seperator = "-".repeat(longest_entry);

        let formatted = entries
            .into_iter()
            .map(|entry| entry.map(|s| s.to_string()).unwrap_or(seperator.clone()))
            .collect::<Vec<_>>()
            .join("\n");

        write!(f, "{formatted}")
    }
}

#[derive(Default)]
pub struct Table {
    headers: Vec<String>,
    rows: Vec<Vec<String>>,
}

impl Table {
    pub fn add_header(&mut self, header: impl ToString) {
        self.headers.push(header.to_string());
    }

    pub fn add_row(&mut self, row: Vec<impl ToString>) -> Result<()> {
        if self.headers.len() != row.len() {
            anyhow::bail!("Row length does not match header length");
        }
        self.rows
            .push(row.into_iter().map(|x| x.to_string()).collect());
        Ok(())
    }
}

impl Display for Table {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut longest_columns = self
            .headers
            .iter()
            .enumerate()
            .map(|(column_id, x)| (column_id, x.len()))
            .collect::<HashMap<_, _>>();

        for row in self.rows.iter() {
            for (column_id, value) in row.iter().enumerate() {
                longest_columns
                    .entry(column_id)
                    .and_modify(|x| *x = max(*x, value.len()));
            }
        }
        let separator = self
            .headers
            .iter()
            .enumerate()
            .map(|(column_id, _)| "-".repeat(longest_columns[&column_id]))
            .collect::<Vec<_>>()
            .join("-|-");

        let mut table = vec![
            self.headers
                .iter()
                .enumerate()
                .map(|(column_id, header)| {
                    let padding = " ".repeat(longest_columns[&column_id] - header.len());
                    format!("{}{}", header, padding)
                })
                .collect::<Vec<_>>()
                .join(" | "),
            separator.clone(),
        ];

        for row in &self.rows {
            table.push(
                row.iter()
                    .enumerate()
                    .map(|(column_id, value)| {
                        let padding = " ".repeat(longest_columns[&column_id] - value.len());
                        format!("{}{}", value, padding)
                    })
                    .collect::<Vec<_>>()
                    .join(" | "),
            );
            table.push(separator.clone());
        }

        let formatted = table.join("\n");

        write!(f, "{formatted}")
    }
}