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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
use std::io::Result;

use termcolor::{Buffer, BufferWriter, Color, ColorChoice, ColorSpec};

use crate::{
    buffers::Buffers,
    display::TableDisplay,
    row::{Dimension as RowDimension, Row, RowStruct},
    style::{Style, StyleStruct},
    utils::*,
};

/// Struct for building a table on command line
pub struct TableStruct {
    /// Title row of the table
    title: Option<RowStruct>,
    /// Rows in the table
    rows: Vec<RowStruct>,
    /// Format of the table
    format: TableFormat,
    /// Style of the table
    style: StyleStruct,
    /// Color preferences for printing the table
    color_choice: ColorChoice,
}

impl TableStruct {
    /// Used to add a title row of a table
    pub fn title<T: Row>(mut self, title: T) -> Self {
        self.title = Some(title.row());
        self
    }

    /// Used to set border of a table
    pub fn border(mut self, border: Border) -> Self {
        self.format.border = border;
        self
    }

    /// Used to set column/row separators of a table
    pub fn separator(mut self, separator: Separator) -> Self {
        self.format.separator = separator;
        self
    }

    /// Used to set the color preferences for printing the table
    pub fn color_choice(mut self, color_choice: ColorChoice) -> Self {
        self.color_choice = color_choice;
        self
    }

    /// Returns a struct which implements the `Display` trait
    pub fn display(&self) -> Result<TableDisplay> {
        let writer = BufferWriter::stdout(self.color_choice);
        let buffers = self.buffers(&writer)?;

        let mut output = Vec::new();

        for buffer in buffers {
            output.append(&mut buffer.into_inner());
        }

        Ok(TableDisplay::new(output))
    }

    /// Prints current table to `stdout`
    pub(crate) fn print_stdout(&self) -> Result<()> {
        self.print_writer(BufferWriter::stdout(self.color_choice))
    }

    /// Prints current table to `stderr`
    pub(crate) fn print_stderr(&self) -> Result<()> {
        self.print_writer(BufferWriter::stderr(self.color_choice))
    }

    fn color_spec(&self) -> ColorSpec {
        self.style.color_spec()
    }

    fn required_dimension(&self) -> Dimension {
        let mut heights = Vec::with_capacity(self.rows.len() + 1);
        let mut widths = Vec::new();

        let title_dimension = self.title.as_ref().map(RowStruct::required_dimension);

        if let Some(title_dimension) = title_dimension {
            widths = title_dimension.widths;
            heights.push(title_dimension.height);
        }

        for row in self.rows.iter() {
            let row_dimension = row.required_dimension();

            heights.push(row_dimension.height);

            let new_widths = row_dimension.widths;

            if widths.is_empty() {
                widths = new_widths;
            } else {
                for (width, new_width) in widths.iter_mut().zip(new_widths.into_iter()) {
                    *width = std::cmp::max(new_width, *width);
                }
            }
        }

        Dimension { widths, heights }
    }

    fn buffers(&self, writer: &BufferWriter) -> Result<Vec<Buffer>> {
        let table_dimension = self.required_dimension();
        let row_dimensions: Vec<RowDimension> = table_dimension.clone().into();
        let mut row_dimensions = row_dimensions.into_iter();
        let color_spec = self.color_spec();

        let mut buffers = Buffers::new(writer);

        print_horizontal_line(
            &mut buffers,
            self.format.border.top.as_ref(),
            &table_dimension,
            &self.format,
            &color_spec,
        )?;

        if let Some(ref title) = self.title {
            let title_dimension = row_dimensions.next().unwrap();
            let mut title_buffers =
                title.buffers(writer, title_dimension, &self.format, &color_spec)?;

            buffers.append(&mut title_buffers)?;

            if self.format.separator.title.is_some() {
                print_horizontal_line(
                    &mut buffers,
                    self.format.separator.title.as_ref(),
                    &table_dimension,
                    &self.format,
                    &color_spec,
                )?
            } else {
                print_horizontal_line(
                    &mut buffers,
                    self.format.separator.row.as_ref(),
                    &table_dimension,
                    &self.format,
                    &color_spec,
                )?
            }
        }

        let mut rows = self.rows.iter().zip(row_dimensions).peekable();

        while let Some((row, row_dimension)) = rows.next() {
            let mut row_buffers = row.buffers(writer, row_dimension, &self.format, &color_spec)?;

            buffers.append(&mut row_buffers)?;

            match rows.peek() {
                Some(_) => print_horizontal_line(
                    &mut buffers,
                    self.format.separator.row.as_ref(),
                    &table_dimension,
                    &self.format,
                    &color_spec,
                )?,
                None => print_horizontal_line(
                    &mut buffers,
                    self.format.border.bottom.as_ref(),
                    &table_dimension,
                    &self.format,
                    &color_spec,
                )?,
            }
        }

        buffers.into_vec()
    }

    fn print_writer(&self, writer: BufferWriter) -> Result<()> {
        let buffers = self.buffers(&writer)?;

        for buffer in buffers.iter() {
            writer.print(buffer)?;
        }

        Ok(())
    }
}

/// Trait to convert raw type into table
pub trait Table {
    /// Converts raw type to a table
    fn table(self) -> TableStruct;
}

impl<T, R> Table for T
where
    T: IntoIterator<Item = R>,
    R: Row,
{
    fn table(self) -> TableStruct {
        let rows = self.into_iter().map(Row::row).collect();

        TableStruct {
            title: Default::default(),
            rows,
            format: Default::default(),
            style: Default::default(),
            color_choice: ColorChoice::Always,
        }
    }
}

impl Table for TableStruct {
    fn table(self) -> TableStruct {
        self
    }
}

impl Style for TableStruct {
    fn foreground_color(mut self, foreground_color: Option<Color>) -> Self {
        self.style = self.style.foreground_color(foreground_color);
        self
    }

    fn background_color(mut self, background_color: Option<Color>) -> Self {
        self.style = self.style.background_color(background_color);
        self
    }

    fn bold(mut self, bold: bool) -> Self {
        self.style = self.style.bold(bold);
        self
    }

    fn underline(mut self, underline: bool) -> Self {
        self.style = self.style.underline(underline);
        self
    }

    fn italic(mut self, italic: bool) -> Self {
        self.style = self.style.italic(italic);
        self
    }

    fn intense(mut self, intense: bool) -> Self {
        self.style = self.style.intense(intense);
        self
    }

    fn dimmed(mut self, dimmed: bool) -> Self {
        self.style = self.style.dimmed(dimmed);
        self
    }
}

/// A vertical line in a table (border or column separator)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct VerticalLine {
    pub(crate) filler: char,
}

impl Default for VerticalLine {
    fn default() -> Self {
        Self { filler: '|' }
    }
}

impl VerticalLine {
    /// Creates a new instance of vertical line
    pub fn new(filler: char) -> Self {
        Self { filler }
    }
}

/// A horizontal line in a table (border or row separator)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HorizontalLine {
    pub(crate) left_end: char,
    pub(crate) right_end: char,
    pub(crate) junction: char,
    pub(crate) filler: char,
}

impl Default for HorizontalLine {
    fn default() -> Self {
        Self {
            left_end: '+',
            right_end: '+',
            junction: '+',
            filler: '-',
        }
    }
}

impl HorizontalLine {
    /// Creates a new instance of horizontal line
    pub fn new(left_end: char, right_end: char, junction: char, filler: char) -> Self {
        Self {
            left_end,
            right_end,
            junction,
            filler,
        }
    }
}

/// Borders of a table
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct Border {
    pub(crate) top: Option<HorizontalLine>,
    pub(crate) bottom: Option<HorizontalLine>,
    pub(crate) left: Option<VerticalLine>,
    pub(crate) right: Option<VerticalLine>,
}

impl Border {
    /// Creates a new builder for border
    pub fn builder() -> BorderBuilder {
        BorderBuilder(Border {
            top: None,
            bottom: None,
            left: None,
            right: None,
        })
    }
}

impl Default for Border {
    fn default() -> Self {
        Self {
            top: Some(Default::default()),
            bottom: Some(Default::default()),
            left: Some(Default::default()),
            right: Some(Default::default()),
        }
    }
}

/// Builder for border
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BorderBuilder(Border);

impl BorderBuilder {
    /// Set top border of a table
    pub fn top(mut self, top: HorizontalLine) -> Self {
        self.0.top = Some(top);
        self
    }

    /// Set bottom border of a table
    pub fn bottom(mut self, bottom: HorizontalLine) -> Self {
        self.0.bottom = Some(bottom);
        self
    }

    /// Set left border of a table
    pub fn left(mut self, left: VerticalLine) -> Self {
        self.0.left = Some(left);
        self
    }

    /// Set right border of a table
    pub fn right(mut self, right: VerticalLine) -> Self {
        self.0.right = Some(right);
        self
    }

    /// Build border
    pub fn build(self) -> Border {
        self.0
    }
}

/// Inner (column/row) separators of a table
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct Separator {
    pub(crate) column: Option<VerticalLine>,
    pub(crate) row: Option<HorizontalLine>,
    pub(crate) title: Option<HorizontalLine>,
}

impl Separator {
    /// Creates a new builder for separator
    pub fn builder() -> SeparatorBuilder {
        SeparatorBuilder(Separator {
            column: None,
            row: None,
            title: None,
        })
    }
}

impl Default for Separator {
    fn default() -> Self {
        Self {
            column: Some(Default::default()),
            row: Some(Default::default()),
            title: None,
        }
    }
}

/// Builder for separator
#[derive(Debug)]
pub struct SeparatorBuilder(Separator);

impl SeparatorBuilder {
    /// Set column separators of a table
    pub fn column(mut self, column: Option<VerticalLine>) -> Self {
        self.0.column = column;
        self
    }

    /// Set column separators of a table
    pub fn row(mut self, row: Option<HorizontalLine>) -> Self {
        self.0.row = row;
        self
    }

    /// Set title of a table
    ///
    /// # None
    ///
    /// When title separator is not preset (i.e., it is `None`), row separator is displayed in place of title separator.
    pub fn title(mut self, title: Option<HorizontalLine>) -> Self {
        self.0.title = title;
        self
    }

    /// Build separator
    pub fn build(self) -> Separator {
        self.0
    }
}

/// Struct for configuring a table's format
#[derive(Debug, Default, Copy, Clone)]
pub(crate) struct TableFormat {
    pub(crate) border: Border,
    pub(crate) separator: Separator,
}

/// Dimensions of a table
#[derive(Debug, Clone, Eq, PartialEq, Default)]
pub(crate) struct Dimension {
    /// Widths of each column of table
    pub(crate) widths: Vec<usize>,
    /// Height of each row of table
    pub(crate) heights: Vec<usize>,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_row_from_str_arr() {
        let table: TableStruct = vec![&["Hello", "World"], &["Scooby", "Doo"]].table();
        assert_eq!(2, table.rows.len());
        assert_eq!(2, table.rows[0].cells.len());
        assert_eq!(2, table.rows[1].cells.len());
    }
}