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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
use crate::debug::inspect_table::{
    global_horizontal_char::SetHorizontalChar, set_widths::SetWidths,
};
use nu_protocol::Value;
use nu_table::{string_width, string_wrap};
use tabled::{
    grid::config::ColoredConfig,
    settings::{peaker::PriorityMax, width::Wrap, Settings, Style},
    Table,
};

pub fn build_table(value: Value, description: String, termsize: usize) -> String {
    let (head, mut data) = util::collect_input(value);
    let count_columns = head.len();
    data.insert(0, head);

    let mut desc = description;
    let mut desc_width = string_width(&desc);
    let mut desc_table_width = get_total_width_2_column_table(11, desc_width);

    let cfg = Table::default().with(Style::modern()).get_config().clone();
    let mut widths = get_data_widths(&data, count_columns);
    truncate_data(&mut data, &mut widths, &cfg, termsize);

    let val_table_width = get_total_width2(&widths, &cfg);
    if val_table_width < desc_table_width {
        increase_widths(&mut widths, desc_table_width - val_table_width);
        increase_data_width(&mut data, &widths);
    }

    if val_table_width > desc_table_width {
        desc_width += val_table_width - desc_table_width;
        increase_string_width(&mut desc, desc_width);
    }

    if desc_table_width > termsize {
        let delete_width = desc_table_width - termsize;
        if delete_width >= desc_width {
            // we can't fit in a description; we consider it's no point in showing then?
            return String::new();
        }

        desc_width -= delete_width;
        desc = string_wrap(&desc, desc_width, false);
        desc_table_width = termsize;
    }

    add_padding_to_widths(&mut widths);

    let width = val_table_width.max(desc_table_width).min(termsize);

    let mut desc_table = Table::from_iter([[String::from("description"), desc]]);
    desc_table.with(Style::rounded().remove_bottom().remove_horizontals());

    let mut val_table = Table::from_iter(data);
    val_table.with(
        Settings::default()
            .with(Style::rounded().corner_top_left('├').corner_top_right('┤'))
            .with(SetWidths(widths))
            .with(Wrap::new(width).priority::<PriorityMax>())
            .with(SetHorizontalChar::new('┼', '┴', 11 + 2 + 1)),
    );

    format!("{desc_table}\n{val_table}")
}

fn get_data_widths(data: &[Vec<String>], count_columns: usize) -> Vec<usize> {
    let mut widths = vec![0; count_columns];
    for row in data {
        for col in 0..count_columns {
            let text = &row[col];
            let width = string_width(text);
            widths[col] = std::cmp::max(widths[col], width);
        }
    }

    widths
}

fn add_padding_to_widths(widths: &mut [usize]) {
    for width in widths {
        *width += 2;
    }
}

fn increase_widths(widths: &mut [usize], need: usize) {
    let all = need / widths.len();
    let mut rest = need - all * widths.len();

    for width in widths {
        *width += all;

        if rest > 0 {
            *width += 1;
            rest -= 1;
        }
    }
}

fn increase_data_width(data: &mut Vec<Vec<String>>, widths: &[usize]) {
    for row in data {
        for (col, max_width) in widths.iter().enumerate() {
            let text = &mut row[col];
            increase_string_width(text, *max_width);
        }
    }
}

fn increase_string_width(text: &mut String, total: usize) {
    let width = string_width(text);
    let rest = total - width;

    if rest > 0 {
        text.extend(std::iter::repeat(' ').take(rest));
    }
}

fn get_total_width_2_column_table(col1: usize, col2: usize) -> usize {
    const PAD: usize = 1;
    const SPLIT_LINE: usize = 1;
    SPLIT_LINE + PAD + col1 + PAD + SPLIT_LINE + PAD + col2 + PAD + SPLIT_LINE
}

fn truncate_data(
    data: &mut Vec<Vec<String>>,
    widths: &mut Vec<usize>,
    cfg: &ColoredConfig,
    expected_width: usize,
) {
    const SPLIT_LINE_WIDTH: usize = 1;
    const PAD: usize = 2;

    let total_width = get_total_width2(widths, cfg);
    if total_width <= expected_width {
        return;
    }

    let mut width = 0;
    let mut peak_count = 0;
    for column_width in widths.iter() {
        let next_width = width + *column_width + SPLIT_LINE_WIDTH + PAD;
        if next_width >= expected_width {
            break;
        }

        width = next_width;
        peak_count += 1;
    }

    debug_assert!(peak_count < widths.len());

    let left_space = expected_width - width;
    let has_space_for_truncation_column = left_space > PAD;
    if !has_space_for_truncation_column {
        peak_count -= 1;
    }

    remove_columns(data, peak_count);
    widths.drain(peak_count..);
    push_empty_column(data);
    widths.push(1);
}

fn remove_columns(data: &mut Vec<Vec<String>>, peak_count: usize) {
    if peak_count == 0 {
        for row in data {
            row.clear();
        }
    } else {
        for row in data {
            row.drain(peak_count..);
        }
    }
}

fn get_total_width2(widths: &[usize], cfg: &ColoredConfig) -> usize {
    let pad = 2;
    let total = widths.iter().sum::<usize>() + pad * widths.len();
    let countv = cfg.count_vertical(widths.len());
    let margin = cfg.get_margin();

    total + countv + margin.left.size + margin.right.size
}

fn push_empty_column(data: &mut Vec<Vec<String>>) {
    let empty_cell = String::from("‥");
    for row in data {
        row.push(empty_cell.clone());
    }
}

mod util {
    use crate::debug::explain::debug_string_without_formatting;
    use nu_engine::get_columns;
    use nu_protocol::Value;

    /// Try to build column names and a table grid.
    pub fn collect_input(value: Value) -> (Vec<String>, Vec<Vec<String>>) {
        let span = value.span();
        match value {
            Value::Record { val: record, .. } => {
                let (cols, vals): (Vec<_>, Vec<_>) = record.into_owned().into_iter().unzip();
                (
                    cols,
                    vec![vals
                        .into_iter()
                        .map(|s| debug_string_without_formatting(&s))
                        .collect()],
                )
            }
            Value::List { vals, .. } => {
                let mut columns = get_columns(&vals);
                let data = convert_records_to_dataset(&columns, vals);

                if columns.is_empty() {
                    columns = vec![String::from("")];
                }

                (columns, data)
            }
            Value::String { val, .. } => {
                let lines = val
                    .lines()
                    .map(|line| Value::string(line.to_string(), span))
                    .map(|val| vec![debug_string_without_formatting(&val)])
                    .collect();

                (vec![String::from("")], lines)
            }
            Value::Nothing { .. } => (vec![], vec![]),
            value => (
                vec![String::from("")],
                vec![vec![debug_string_without_formatting(&value)]],
            ),
        }
    }

    fn convert_records_to_dataset(cols: &[String], records: Vec<Value>) -> Vec<Vec<String>> {
        if !cols.is_empty() {
            create_table_for_record(cols, &records)
        } else if cols.is_empty() && records.is_empty() {
            vec![]
        } else if cols.len() == records.len() {
            vec![records
                .into_iter()
                .map(|s| debug_string_without_formatting(&s))
                .collect()]
        } else {
            records
                .into_iter()
                .map(|record| vec![debug_string_without_formatting(&record)])
                .collect()
        }
    }

    fn create_table_for_record(headers: &[String], items: &[Value]) -> Vec<Vec<String>> {
        let mut data = vec![Vec::new(); items.len()];

        for (i, item) in items.iter().enumerate() {
            let row = record_create_row(headers, item);
            data[i] = row;
        }

        data
    }

    fn record_create_row(headers: &[String], item: &Value) -> Vec<String> {
        if let Value::Record { val, .. } = item {
            headers
                .iter()
                .map(|col| {
                    val.get(col)
                        .map(debug_string_without_formatting)
                        .unwrap_or_else(String::new)
                })
                .collect()
        } else {
            // should never reach here due to `get_columns` above which will return
            // empty columns if any value in the list is not a record
            vec![String::new(); headers.len()]
        }
    }
}

mod global_horizontal_char {
    use tabled::{
        grid::{
            config::{ColoredConfig, Offset},
            dimension::{CompleteDimensionVecRecords, Dimension},
            records::{ExactRecords, Records},
        },
        settings::TableOption,
    };

    pub struct SetHorizontalChar {
        intersection: char,
        split: char,
        index: usize,
    }

    impl SetHorizontalChar {
        pub fn new(intersection: char, split: char, index: usize) -> Self {
            Self {
                intersection,
                split,
                index,
            }
        }
    }

    impl<R: Records + ExactRecords> TableOption<R, CompleteDimensionVecRecords<'_>, ColoredConfig>
        for SetHorizontalChar
    {
        fn change(
            self,
            records: &mut R,
            cfg: &mut ColoredConfig,
            dimension: &mut CompleteDimensionVecRecords<'_>,
        ) {
            let count_columns = records.count_columns();
            let count_rows = records.count_rows();

            if count_columns == 0 || count_rows == 0 {
                return;
            }

            let widths = get_widths(dimension, records.count_columns());

            let has_vertical = cfg.has_vertical(0, count_columns);
            if has_vertical && self.index == 0 {
                let mut border = cfg.get_border((0, 0), (count_rows, count_columns));
                border.left_top_corner = Some(self.intersection);
                cfg.set_border((0, 0), border);
                return;
            }

            let mut i = 1;
            for (col, width) in widths.into_iter().enumerate() {
                if self.index < i + width {
                    let o = self.index - i;
                    cfg.set_horizontal_char((0, col), self.split, Offset::Begin(o));
                    return;
                }

                i += width;

                let has_vertical = cfg.has_vertical(col, count_columns);
                if has_vertical {
                    if self.index == i {
                        let mut border = cfg.get_border((0, col), (count_rows, count_columns));
                        border.right_top_corner = Some(self.intersection);
                        cfg.set_border((0, col), border);
                        return;
                    }

                    i += 1;
                }
            }
        }
    }

    fn get_widths(dims: &CompleteDimensionVecRecords<'_>, count_columns: usize) -> Vec<usize> {
        let mut widths = vec![0; count_columns];
        for (col, width) in widths.iter_mut().enumerate() {
            *width = dims.get_width(col);
        }

        widths
    }
}

mod set_widths {
    use tabled::{
        grid::{config::ColoredConfig, dimension::CompleteDimensionVecRecords},
        settings::TableOption,
    };

    pub struct SetWidths(pub Vec<usize>);

    impl<R> TableOption<R, CompleteDimensionVecRecords<'_>, ColoredConfig> for SetWidths {
        fn change(
            self,
            _: &mut R,
            _: &mut ColoredConfig,
            dims: &mut CompleteDimensionVecRecords<'_>,
        ) {
            dims.set_widths(self.0);
        }
    }
}