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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
//! The purpose of term-table is to make it easy for CLI apps to display data in a table format
//!# Example
//! Here is an example of how to create a simple table
//!```
//! use term_data_table::{ Table, Cell, TableStyle, Alignment, Row };
//!
//! let table = Table::new()
//!     .with_style(TableStyle::EXTENDED)
//!     .with_row(Row::new().with_cell(
//!         Cell::from("This is some centered text")
//!             .with_alignment(Alignment::Center)
//!             .with_col_span(2)
//!     ))
//!     .with_row(Row::new().with_cell(
//!         Cell::from("This is left aligned text")
//!     ).with_cell(
//!         Cell::from("This is right aligned text")
//!             .with_alignment(Alignment::Right)
//!     ))
//!     .with_row(Row::new().with_cell(
//!         Cell::from("This is left aligned text")
//!     ).with_cell(
//!         Cell::from("This is right aligned text")
//!             .with_alignment(Alignment::Right)
//!     ))
//!     .with_row(Row::new().with_cell(
//!         Cell::from("This is some really really really really really really really really really that is going to wrap to the next line")
//!             .with_col_span(2)
//!     ));
//!println!("{}", table.fixed_width(80));
//!```
//!
//!### This is the result
//!
//!<pre>
//! ╔═════════════════════════════════════════════════════════════════════════════════╗
//! ║                            This is some centered text                           ║
//! ╠════════════════════════════════════════╦════════════════════════════════════════╣
//! ║ This is left aligned text              ║             This is right aligned text ║
//! ╠════════════════════════════════════════╬════════════════════════════════════════╣
//! ║ This is left aligned text              ║             This is right aligned text ║
//! ╠════════════════════════════════════════╩════════════════════════════════════════╣
//! ║ This is some really really really really really really really really really tha ║
//! ║ t is going to wrap to the next line                                             ║
//! ╚═════════════════════════════════════════════════════════════════════════════════╝
//!</pre>

#[macro_use]
extern crate lazy_static;

mod cell;
mod row;
mod ser;
mod style;

pub use crate::{
    cell::{Alignment, Cell},
    row::{IntoRow, Row},
    style::TableStyle,
};
// TODO just use a serde deserializer.
#[doc(inline)]
pub use term_data_table_derive::IntoRow;

use itertools::Itertools;
use serde::Serialize;
use std::{cell::RefCell, collections::HashMap, fmt};
use terminal_size::terminal_size;

thread_local! {
    /// Used to calculate the maximum width of table cells.
    static MAX_WIDTHS_CELL_WIDTHS: RefCell<(ColumnWidths, HashMap<usize, usize>)>
        = RefCell::new((ColumnWidths::new(), HashMap::new()));
}

/// Represents the vertical position of a row
#[derive(Eq, PartialEq, Copy, Clone)]
pub enum RowPosition {
    First,
    Mid,
    Last,
}

/// A set of rows containing data
#[derive(Clone, Debug)]
pub struct Table<'data> {
    rows: Vec<Row<'data>>,
    style: TableStyle,
    /// Whether or not to vertically separate rows in the table.
    ///
    /// Defaults to `true`.
    pub has_separate_rows: bool,
    /// Whether the table should have a top border.
    ///
    /// Setting `has_separator` to false on the first row will have the same effect as setting this
    /// to false
    ///
    /// Defaults to `true`.
    pub has_top_border: bool,
    /// Whether the table should have a bottom border
    ///
    /// Defaults to `true`.
    pub has_bottom_border: bool,

    /// Calculated column widths.
    column_widths: RefCell<ColumnWidths>,
    /// Calculated row lines
    row_lines: RefCell<Vec<usize>>,
}

impl<'data> Default for Table<'data> {
    fn default() -> Self {
        Self {
            rows: Vec::new(),
            style: TableStyle::EXTENDED,
            has_separate_rows: true,
            has_top_border: true,
            has_bottom_border: true,

            column_widths: RefCell::new(ColumnWidths::new()),
            row_lines: RefCell::new(vec![]),
        }
    }
}

impl<'data> Table<'data> {
    pub fn new() -> Table<'data> {
        Default::default()
    }

    pub fn from_rows(rows: Vec<Row<'data>>) -> Table<'data> {
        Self {
            rows,
            ..Default::default()
        }
    }

    pub fn from_serde(data: impl IntoIterator<Item = impl Serialize>) -> anyhow::Result<Self> {
        let mut table = Table::new();
        for row in data {
            table.add_row(ser::serialize_row(row)?);
        }
        Ok(table)
    }

    /// Add a row
    pub fn with_row(mut self, row: Row<'data>) -> Self {
        self.add_row(row);
        self
    }

    /// Add a row
    pub fn add_row(&mut self, row: Row<'data>) -> &mut Self {
        self.rows.push(row);
        self
    }

    pub fn with_style(mut self, style: TableStyle) -> Self {
        self.set_style(style);
        self
    }

    pub fn set_style(&mut self, style: TableStyle) -> &mut Self {
        self.style = style;
        self
    }

    /*
    pub fn max_column_width(&self) -> usize {
        self.max_column_width
    }

    pub fn set_max_column_width(&mut self, max_column_width: usize) -> &mut Self {
        self.max_column_width = max_column_width;
        self
    }

    pub fn with_max_column_width(mut self, max_column_width: usize) -> Self {
        self.set_max_column_width(max_column_width);
        self
    }

    /// Set the max width of a particular column
    ///
    /// Overrides any value set for `max_column_width`.
    pub fn set_max_width_for_column(&mut self, column_index: usize, max_width: usize) -> &mut Self {
        self.max_column_widths.insert(column_index, max_width);
        self
    }

    pub fn with_max_width_for_column(mut self, column_index: usize, max_width: usize) -> Self {
        self.set_max_width_for_column(column_index, max_width);
        self
    }
    */

    pub fn has_separate_rows(&self) -> bool {
        self.has_separate_rows
    }

    pub fn with_separate_rows(mut self, has_separate_rows: bool) -> Self {
        self.set_separate_rows(has_separate_rows);
        self
    }

    pub fn set_separate_rows(&mut self, has_separate_rows: bool) -> &mut Self {
        self.has_separate_rows = has_separate_rows;
        self
    }

    /// Decide how much space to give each cell and layout the rows.
    ///
    /// If no width is given, all cells will be the largest of their contents.
    ///
    fn layout(&self, width: Option<usize>) {
        // We need to know the maxiumum number of columns in a row.
        let cols = self.rows.iter().map(|row| row.columns()).max().unwrap_or(0);
        let border_width = self.style.border_width();
        let mut col_widths = self.column_widths.borrow_mut();
        col_widths.reset(cols);

        // short-circuit when there are no columns
        if cols == 0 {
            return;
        }

        if let Some(width) = width {
            // total space available for drawing text
            let cell_width_total = width - (border_width + 1) * cols;

            MAX_WIDTHS_CELL_WIDTHS.with(|lk| {
                let (ref mut max_widths, ref mut cell_widths) = &mut *lk.borrow_mut();
                // reset
                max_widths.reset(cols);
                cell_widths.clear();

                // first stash the max space each column will need.
                for row in self.rows.iter() {
                    max_widths.fit_row_singleline(row, border_width);
                }

                // Next, calculate the width we would give each cell if we were splitting space
                // evenly
                let cell_width = cell_width_total / cols;

                // Next, find all cells with max width less than the cell width we calculated and
                // give them their max width
                for (idx, max_width) in max_widths.iter().enumerate() {
                    if *max_width < cell_width {
                        cell_widths.insert(idx, *max_width);
                    }
                }

                let remaining_cells = cols - cell_widths.len();
                let remaining_space =
                    cell_width_total - cell_widths.values().copied().sum::<usize>();
                if remaining_cells > 0 {
                    let cell_width = remaining_space / remaining_cells;
                    for idx in 0..cols {
                        cell_widths.entry(idx).or_insert(cell_width);
                    }
                }

                col_widths.from_map(cell_widths);
            });
        } else {
            // Give all cells all the space they need.
            for row in self.rows.iter() {
                col_widths.fit_row_singleline(row, border_width);
            }
        }
        for row in self.rows.iter() {
            self.row_lines
                .borrow_mut()
                .push(row.layout(&*col_widths, border_width));
        }
    }

    /// Write the table out to a formatter.
    ///
    /// This method calculates stale state that it needs.
    ///
    /// # Params
    ///  - `view_width` - the width of the viewport we are rendering to, if any. If unspecified,
    ///    we will assume infinite width.
    fn render(&self, view_width: Option<usize>, f: &mut fmt::Formatter) -> fmt::Result {
        self.layout(view_width);
        if self.rows.is_empty() {
            return writeln!(f, "<empty table>");
        }
        let row_lines = self.row_lines.borrow();

        if self.has_top_border {
            self.rows[0].render_top_separator(&*self.column_widths.borrow(), &self.style, f)?;
        }
        self.rows[0].render_content(&*self.column_widths.borrow(), row_lines[0], &self.style, f)?;

        for (idx, (prev_row, row)) in self.rows.iter().tuple_windows().enumerate() {
            if self.has_separate_rows {
                row.render_separator(prev_row, &*self.column_widths.borrow(), &self.style, f)?;
            }

            let row_lines = self.row_lines.borrow();
            row.render_content(
                &*self.column_widths.borrow(),
                row_lines[idx + 1],
                &self.style,
                f,
            )?;
        }
        if self.has_bottom_border {
            self.rows[self.rows.len() - 1].render_bottom_separator(
                &*self.column_widths.borrow(),
                &self.style,
                f,
            )?;
        }
        Ok(())
    }

    /// Get the terminal width and use this for the table width.
    ///
    /// # Panics
    ///
    /// Will panic if it cannot get the terminal width (e.g. because we aren't in a terminal).
    pub fn for_terminal(&self) -> impl fmt::Display + '_ {
        match terminal_size().and_then(|v| usize::try_from((v.0).0).ok()) {
            Some(width) => FixedWidth { table: self, width },
            None => FixedWidth {
                table: self,
                width: usize::MAX,
            },
        }
    }

    /// Use a custom value for the table width
    pub fn fixed_width(&self, width: usize) -> impl fmt::Display + '_ {
        FixedWidth { table: self, width }
    }
}

struct FixedWidth<'a> {
    table: &'a Table<'a>,
    width: usize,
}

impl fmt::Display for FixedWidth<'_> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.table.render(Some(self.width), f)
    }
}

impl<'data> fmt::Display for Table<'data> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.render(None, f)
    }
}

pub fn data_table<'a, R: 'a>(input: impl IntoIterator<Item = &'a R>) -> Table<'a>
where
    R: IntoRow,
{
    let mut table = Table::new();
    for row in input {
        table.add_row(row.into_row());
    }
    table
}

#[derive(Debug, Clone)]
struct ColumnWidths(Vec<usize>);

impl ColumnWidths {
    fn new() -> Self {
        ColumnWidths(vec![])
    }

    /// Reset all columns to 0 and make sure there are the correct number of columns.
    fn reset(&mut self, num_cols: usize) {
        self.0.clear();
        self.0.resize(num_cols, 0);
    }

    /// Make our widths fit the given row with all text on a single line.
    ///
    /// This is for when we are allowed to use as much space as we want.
    fn fit_row_singleline(&mut self, row: &Row, border_width: usize) {
        let mut idx = 0;
        for cell in row.cells.iter() {
            if cell.col_span == 1 {
                self.0[idx] = self.0[idx].max(cell.min_width(true));
            } else {
                // space required to fit this cell (taking into account we have some borders to
                // use).
                let required_width = cell.min_width(true) - border_width * (cell.col_span - 1);
                let floor_per_cell = required_width / cell.col_span;
                // space we need to put somewhere
                let mut to_fit = required_width % cell.col_span;
                // split space evenly, with remainder in last space.
                for i in 0..cell.col_span {
                    let extra = if to_fit > 0 { 1 } else { 0 };
                    to_fit = to_fit.saturating_sub(1);
                    self.0[idx + i] = self.0[idx + 1].max(floor_per_cell + extra);
                }
            }
            idx += cell.col_span;
        }
    }

    fn from_map(&mut self, map: &HashMap<usize, usize>) {
        for (idx, slot) in self.0.iter_mut().enumerate() {
            *slot = *map.get(&idx).unwrap();
        }
    }
}

impl std::ops::Deref for ColumnWidths {
    type Target = [usize];
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

#[cfg(test)]
mod test {

    use crate::cell::{Alignment, Cell};
    use crate::row::Row;
    use crate::Table;
    use crate::TableStyle;
    use pretty_assertions::assert_eq;

    #[test]
    fn correct_default_padding() {
        let table = Table::new()
            .with_separate_rows(false)
            .with_style(TableStyle::SIMPLE)
            .with_row(
                Row::new()
                    .with_cell(Cell::from("A").with_alignment(Alignment::Center))
                    .with_cell(Cell::from("B").with_alignment(Alignment::Center)),
            )
            .with_row(
                Row::new()
                    .with_cell(Cell::from(1.to_string()))
                    .with_cell(Cell::from("1")),
            )
            .with_row(
                Row::new()
                    .with_cell(Cell::from(2.to_string()))
                    .with_cell(Cell::from("10")),
            )
            .with_row(
                Row::new()
                    .with_cell(Cell::from(3.to_string()))
                    .with_cell(Cell::from("100")),
            );
        let expected = r"+---+-----+
| A |  B  |
| 1 | 1   |
| 2 | 10  |
| 3 | 100 |
+---+-----+
";
        println!("{}", table);
        assert_eq!(expected, table.to_string());
    }

    #[test]
    fn uneven_center_alignment() {
        let table = Table::new()
            .with_separate_rows(false)
            .with_style(TableStyle::SIMPLE)
            .with_row(Row::new().with_cell(Cell::from("A").with_alignment(Alignment::Center)))
            .with_row(Row::new().with_cell(Cell::from(11.to_string())))
            .with_row(Row::new().with_cell(Cell::from(2.to_string())))
            .with_row(Row::new().with_cell(Cell::from(3.to_string())));
        let expected = r"+----+
| A  |
| 11 |
| 2  |
| 3  |
+----+
";
        println!("{}", table);
        assert_eq!(expected, table.to_string());
    }

    #[test]
    fn uneven_center_alignment_2() {
        let table = Table::new()
            .with_separate_rows(false)
            .with_style(TableStyle::SIMPLE)
            .with_row(
                Row::new()
                    .with_cell(Cell::from("A1").with_alignment(Alignment::Center))
                    .with_cell(Cell::from("B").with_alignment(Alignment::Center)),
            );
        println!("{}", table);
        let expected = r"+----+---+
| A1 | B |
+----+---+
";
        assert_eq!(expected, table.to_string());
    }

    #[test]
    fn simple_table_style() {
        let mut table = Table::new().with_style(TableStyle::SIMPLE);

        add_data_to_test_table(&mut table);

        let expected = r"+-----------------------------------------------------------------------------+
|                         This is some centered text                          |
+--------------------------------------+--------------------------------------+
| This is left aligned text            |           This is right aligned text |
+--------------------------------------+--------------------------------------+
| This is left aligned text            |           This is right aligned text |
+--------------------------------------+--------------------------------------+
| This is some really really really really really really really really        |
| really that is going to wrap to the next line                               |
+-----------------------------------------------------------------------------+
| aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa |
| aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa                                     |
+-----------------------------------------------------------------------------+
";
        let table = table.fixed_width(80);
        println!("{}", table.to_string());
        assert_eq!(expected, table.to_string());
    }

    #[test]
    #[ignore]
    fn uneven_with_varying_col_span() {
        let table = Table::new()
            .with_separate_rows(true)
            .with_style(TableStyle::SIMPLE)
            .with_row(
                Row::new()
                    .with_cell(Cell::from("A1111111").with_alignment(Alignment::Center))
                    .with_cell(Cell::from("B").with_alignment(Alignment::Center)),
            )
            .with_row(
                Row::new()
                    .with_cell(Cell::from(1.to_string()))
                    .with_cell(Cell::from("1")),
            )
            .with_row(
                Row::new()
                    .with_cell(Cell::from(2.to_string()))
                    .with_cell(Cell::from("10")),
            )
            .with_row(
                Row::new()
                    .with_cell(
                        Cell::from(3.to_string())
                            .with_alignment(Alignment::Left)
                            .with_padding(false),
                    )
                    .with_cell(Cell::from("100")),
            )
            .with_row(Row::new().with_cell(Cell::from("S").with_alignment(Alignment::Center)));
        let expected = "+----------+-----+
| A1111111 |  B  |
+----------+-----+
| 1        | 1   |
+----------+-----+
| 2        | 10  |
+----------+-----+
|\03\0         | 100 |
+----------+-----+
|        S       |
+----------------+
";
        println!("{}", table);
        assert_eq!(expected.trim(), table.to_string().trim());
    }

    // TODO - The output of this test isn't ideal. There is probably a better way to calculate the
    // the column/row layout that would improve this
    #[test]
    fn uneven_with_varying_col_span_2() {
        let table = Table::new()
            .with_separate_rows(false)
            .with_style(TableStyle::SIMPLE)
            .with_row(
                Row::new()
                    .with_cell(Cell::from("A").with_alignment(Alignment::Center))
                    .with_cell(Cell::from("B").with_alignment(Alignment::Center)),
            )
            .with_row(
                Row::new()
                    .with_cell(Cell::from(1.to_string()))
                    .with_cell(Cell::from("1")),
            )
            .with_row(
                Row::new()
                    .with_cell(Cell::from(2.to_string()))
                    .with_cell(Cell::from("10")),
            )
            .with_row(
                Row::new()
                    .with_cell(Cell::from(3.to_string()))
                    .with_cell(Cell::from("100")),
            )
            .with_row(
                Row::new().with_cell(
                    Cell::from("Spanner")
                        .with_col_span(2)
                        .with_alignment(Alignment::Center),
                ),
            );
        let expected = "+-----+-----+
|  A  |  B  |
| 1   | 1   |
| 2   | 10  |
| 3   | 100 |
|  Spanner  |
+-----------+
";
        println!("{}", table);
        assert_eq!(expected.trim(), table.to_string().trim());
    }

    /*
        #[test]
        fn extended_table_style_wrapped() {
            let table = Table::new()
                .with_max_column_width(40)
                .with_max_widths_for_columns([(0, 1), (1, 1)])

            .with_style ( TableStyle::EXTENDED)

            .with_row(Row::new(vec![Cell::new_with_alignment(
                "This is some centered text",
                2,
                Alignment::Center,
            )]))

            .with_row(Row::new(vec![
                Cell::new("This is left aligned text"),
                Cell::new_with_alignment("This is right aligned text", 1, Alignment::Right),
            ]))

            .with_row(Row::new(vec![
                Cell::new("This is left aligned text"),
                Cell::new_with_alignment("This is right aligned text", 1, Alignment::Right),
            ]))

            .with_row(Row::new(vec![
                Cell::new_with_col_span("This is some really really really really really really really really really that is going to wrap to the next line\n1\n2", 2),
            ]));

            let expected = r"╔═══════╗
    ║ This  ║
    ║ is so ║
    ║ me ce ║
    ║ ntere ║
    ║ d tex ║
    ║   t   ║
    ╠═══╦═══╣
    ║ T ║ T ║
    ║ h ║ h ║
    ║ i ║ i ║
    ║ s ║ s ║
    ║   ║   ║
    ║ i ║ i ║
    ║ s ║ s ║
    ║   ║   ║
    ║ l ║ r ║
    ║ e ║ i ║
    ║ f ║ g ║
    ║ t ║ h ║
    ║   ║ t ║
    ║ a ║   ║
    ║ l ║ a ║
    ║ i ║ l ║
    ║ g ║ i ║
    ║ n ║ g ║
    ║ e ║ n ║
    ║ d ║ e ║
    ║   ║ d ║
    ║ t ║   ║
    ║ e ║ t ║
    ║ x ║ e ║
    ║ t ║ x ║
    ║   ║ t ║
    ╠═══╬═══╣
    ║ T ║ T ║
    ║ h ║ h ║
    ║ i ║ i ║
    ║ s ║ s ║
    ║   ║   ║
    ║ i ║ i ║
    ║ s ║ s ║
    ║   ║   ║
    ║ l ║ r ║
    ║ e ║ i ║
    ║ f ║ g ║
    ║ t ║ h ║
    ║   ║ t ║
    ║ a ║   ║
    ║ l ║ a ║
    ║ i ║ l ║
    ║ g ║ i ║
    ║ n ║ g ║
    ║ e ║ n ║
    ║ d ║ e ║
    ║   ║ d ║
    ║ t ║   ║
    ║ e ║ t ║
    ║ x ║ e ║
    ║ t ║ x ║
    ║   ║ t ║
    ╠═══╩═══╣
    ║ This  ║
    ║ is so ║
    ║ me re ║
    ║ ally  ║
    ║ reall ║
    ║ y rea ║
    ║ lly r ║
    ║ eally ║
    ║  real ║
    ║ ly re ║
    ║ ally  ║
    ║ reall ║
    ║ y rea ║
    ║ lly r ║
    ║ eally ║
    ║  that ║
    ║  is g ║
    ║ oing  ║
    ║ to wr ║
    ║ ap to ║
    ║  the  ║
    ║ next  ║
    ║ line  ║
    ║ 1     ║
    ║ 2     ║
    ╚═══════╝
    ";
            println!("{}", table.render());
            assert_eq!(expected, table.render());
        }

            #[test]
            fn elegant_table_style() {
                let mut table = Table::new();
                table.style = TableStyle::elegant();

                add_data_to_test_table(&mut table);

                let expected = r"╔─────────────────────────────────────────────────────────────────────────────────╗
        │                            This is some centered text                           │
        ╠────────────────────────────────────────╦────────────────────────────────────────╣
        │ This is left aligned text              │             This is right aligned text │
        ╠────────────────────────────────────────┼────────────────────────────────────────╣
        │ This is left aligned text              │             This is right aligned text │
        ╠────────────────────────────────────────╩────────────────────────────────────────╣
        │ This is some really really really really really really really really really tha │
        │ t is going to wrap to the next line                                             │
        ╚─────────────────────────────────────────────────────────────────────────────────╝
        ";
                println!("{}", table.render());
                assert_eq!(expected, table.render());
            }

            #[test]
            fn thin_table_style() {
                let mut table = Table::new();
                table.style = TableStyle::thin();

                add_data_to_test_table(&mut table);

                let expected = r"┌─────────────────────────────────────────────────────────────────────────────────┐
        │                            This is some centered text                           │
        ├────────────────────────────────────────┬────────────────────────────────────────┤
        │ This is left aligned text              │             This is right aligned text │
        ├────────────────────────────────────────┼────────────────────────────────────────┤
        │ This is left aligned text              │             This is right aligned text │
        ├────────────────────────────────────────┴────────────────────────────────────────┤
        │ This is some really really really really really really really really really tha │
        │ t is going to wrap to the next line                                             │
        └─────────────────────────────────────────────────────────────────────────────────┘
        ";
                println!("{}", table.render());
                assert_eq!(expected, table.render());
            }

            #[test]
            fn rounded_table_style() {
                let mut table = Table::new();

                table.style = TableStyle::rounded();

                add_data_to_test_table(&mut table);

                let expected = r"╭─────────────────────────────────────────────────────────────────────────────────╮
        │                            This is some centered text                           │
        ├────────────────────────────────────────┬────────────────────────────────────────┤
        │ This is left aligned text              │             This is right aligned text │
        ├────────────────────────────────────────┼────────────────────────────────────────┤
        │ This is left aligned text              │             This is right aligned text │
        ├────────────────────────────────────────┴────────────────────────────────────────┤
        │ This is some really really really really really really really really really tha │
        │ t is going to wrap to the next line                                             │
        ╰─────────────────────────────────────────────────────────────────────────────────╯
        ";
                println!("{}", table.render());
                assert_eq!(expected, table.render());
            }

            #[test]
            fn complex_table() {
                let mut table = Table::new();

                table.add_row(Row::new(vec![
                    Cell::new_with_col_span("Col*1*Span*2", 2),
                    Cell::new("Col 2 Span 1"),
                    Cell::new_with_col_span("Col 3 Span 2", 2),
                    Cell::new("Col 4 Span 1"),
                ]));
                table.add_row(Row::new(vec![
                    Cell::new("Col 1 Span 1"),
                    Cell::new("Col 2 Span 1"),
                    Cell::new("Col 3 Span 1"),
                    Cell::new_with_col_span("Col 4 Span 1", 2),
                ]));
                table.add_row(Row::new(vec![
                    Cell::new("fasdaff"),
                    Cell::new("fff"),
                    Cell::new("fff"),
                ]));
                table.add_row(Row::new(vec![
                    Cell::new_with_alignment("fasdff", 3, Alignment::Right),
                    Cell::new_with_col_span("fffdff", 4),
                ]));
                table.add_row(Row::new(vec![
                    Cell::new("fasdsaff"),
                    Cell::new("fff"),
                    Cell::new("f\nf\nf\nfff\nrrr\n\n\n"),
                ]));
                table.add_row(Row::new(vec![Cell::new("fasdsaff")]));

                let s = table.render().clone();

                table.add_row(Row::new(vec![Cell::new_with_alignment(
                    s,
                    3,
                    Alignment::Left,
                )]));

                let expected = r"╔═════════════════════════════════════════════════════════╦════════════════════════════╦════════════════╦══════════════╦═══╗
        ║ Col*1*Span*2                                            ║ Col 2 Span 1               ║ Col 3 Span 2   ║ Col 4 Span 1 ║   ║
        ╠════════════════════════════╦════════════════════════════╬════════════════════════════╬════════════════╬══════════════╬═══╣
        ║ Col 1 Span 1               ║ Col 2 Span 1               ║ Col 3 Span 1               ║ Col 4 Span 1   ║              ║   ║
        ╠════════════════════════════╬════════════════════════════╬════════════════════════════╬═══════╦════════╬══════════════╬═══╣
        ║ fasdaff                    ║ fff                        ║ fff                        ║       ║        ║              ║   ║
        ╠════════════════════════════╩════════════════════════════╩════════════════════════════╬═══════╩════════╩══════════════╩═══╣
        ║                                                                               fasdff ║ fffdff                            ║
        ╠════════════════════════════╦════════════════════════════╦════════════════════════════╬═══════╦════════╦══════════════╦═══╣
        ║ fasdsaff                   ║ fff                        ║ f                          ║       ║        ║              ║   ║
        ║                            ║                            ║ f                          ║       ║        ║              ║   ║
        ║                            ║                            ║ f                          ║       ║        ║              ║   ║
        ║                            ║                            ║ fff                        ║       ║        ║              ║   ║
        ║                            ║                            ║ rrr                        ║       ║        ║              ║   ║
        ║                            ║                            ║                            ║       ║        ║              ║   ║
        ║                            ║                            ║                            ║       ║        ║              ║   ║
        ║                            ║                            ║                            ║       ║        ║              ║   ║
        ╠════════════════════════════╬════════════════════════════╬════════════════════════════╬═══════╬════════╬══════════════╬═══╣
        ║ fasdsaff                   ║                            ║                            ║       ║        ║              ║   ║
        ╠════════════════════════════╩════════════════════════════╩════════════════════════════╬═══════╬════════╬══════════════╬═══╣
        ║ ╔═════════════════════════════╦══════════════╦════════════════╦══════════════╦═══╗   ║       ║        ║              ║   ║
        ║ ║ Col*1*Span*2                ║ Col 2 Span 1 ║ Col 3 Span 2   ║ Col 4 Span 1 ║   ║   ║       ║        ║              ║   ║
        ║ ╠══════════════╦══════════════╬══════════════╬════════════════╬══════════════╬═══╣   ║       ║        ║              ║   ║
        ║ ║ Col 1 Span 1 ║ Col 2 Span 1 ║ Col 3 Span 1 ║ Col 4 Span 1   ║              ║   ║   ║       ║        ║              ║   ║
        ║ ╠══════════════╬══════════════╬══════════════╬═══════╦════════╬══════════════╬═══╣   ║       ║        ║              ║   ║
        ║ ║ fasdaff      ║ fff          ║ fff          ║       ║        ║              ║   ║   ║       ║        ║              ║   ║
        ║ ╠══════════════╩══════════════╩══════════════╬═══════╩════════╩══════════════╩═══╣   ║       ║        ║              ║   ║
        ║ ║                                     fasdff ║ fffdff                            ║   ║       ║        ║              ║   ║
        ║ ╠══════════════╦══════════════╦══════════════╬═══════╦════════╦══════════════╦═══╣   ║       ║        ║              ║   ║
        ║ ║ fasdsaff     ║ fff          ║ f            ║       ║        ║              ║   ║   ║       ║        ║              ║   ║
        ║ ║              ║              ║ f            ║       ║        ║              ║   ║   ║       ║        ║              ║   ║
        ║ ║              ║              ║ f            ║       ║        ║              ║   ║   ║       ║        ║              ║   ║
        ║ ║              ║              ║ fff          ║       ║        ║              ║   ║   ║       ║        ║              ║   ║
        ║ ║              ║              ║ rrr          ║       ║        ║              ║   ║   ║       ║        ║              ║   ║
        ║ ║              ║              ║              ║       ║        ║              ║   ║   ║       ║        ║              ║   ║
        ║ ║              ║              ║              ║       ║        ║              ║   ║   ║       ║        ║              ║   ║
        ║ ║              ║              ║              ║       ║        ║              ║   ║   ║       ║        ║              ║   ║
        ║ ╠══════════════╬══════════════╬══════════════╬═══════╬════════╬══════════════╬═══╣   ║       ║        ║              ║   ║
        ║ ║ fasdsaff     ║              ║              ║       ║        ║              ║   ║   ║       ║        ║              ║   ║
        ║ ╚══════════════╩══════════════╩══════════════╩═══════╩════════╩══════════════╩═══╝   ║       ║        ║              ║   ║
        ║                                                                                      ║       ║        ║              ║   ║
        ╚══════════════════════════════════════════════════════════════════════════════════════╩═══════╩════════╩══════════════╩═══╝
        ";
                println!("{}", table.render());
                assert_eq!(expected, table.render());
            }

            #[test]
            fn no_top_border() {
                let mut table = Table::new();
                table.style = TableStyle::simple();
                table.has_top_border = false;

                add_data_to_test_table(&mut table);

                let expected = r"|                            This is some centered text                           |
        +----------------------------------------+----------------------------------------+
        | This is left aligned text              |             This is right aligned text |
        +----------------------------------------+----------------------------------------+
        | This is left aligned text              |             This is right aligned text |
        +----------------------------------------+----------------------------------------+
        | This is some really really really really really really really really really tha |
        | t is going to wrap to the next line                                             |
        +---------------------------------------------------------------------------------+
        ";
                println!("{}", table.render());
                assert_eq!(expected, table.render());
            }

            #[test]
            fn no_bottom_border() {
                let mut table = Table::new();
                table.style = TableStyle::simple();
                table.has_bottom_border = false;

                add_data_to_test_table(&mut table);

                let expected = r"+---------------------------------------------------------------------------------+
        |                            This is some centered text                           |
        +----------------------------------------+----------------------------------------+
        | This is left aligned text              |             This is right aligned text |
        +----------------------------------------+----------------------------------------+
        | This is left aligned text              |             This is right aligned text |
        +----------------------------------------+----------------------------------------+
        | This is some really really really really really really really really really tha |
        | t is going to wrap to the next line                                             |
        ";
                println!("{}", table.render());
                assert_eq!(expected, table.render());
            }

            #[test]
            fn no_separators() {
                let mut table = Table::new();
                table.style = TableStyle::simple();
                table.separate_rows = false;

                add_data_to_test_table(&mut table);

                let expected = r"+---------------------------------------------------------------------------------+
        |                            This is some centered text                           |
        | This is left aligned text              |             This is right aligned text |
        | This is left aligned text              |             This is right aligned text |
        | This is some really really really really really really really really really tha |
        | t is going to wrap to the next line                                             |
        +---------------------------------------------------------------------------------+
        ";
                println!("{}", table.render());
                assert_eq!(expected, table.render());
            }

            #[test]
            fn some_rows_no_separators() {
                let mut table = Table::new();
                table.style = TableStyle::simple();

                add_data_to_test_table(&mut table);

                table.rows[2].has_separator = false;

                let expected = r"+---------------------------------------------------------------------------------+
        |                            This is some centered text                           |
        +----------------------------------------+----------------------------------------+
        | This is left aligned text              |             This is right aligned text |
        | This is left aligned text              |             This is right aligned text |
        +----------------------------------------+----------------------------------------+
        | This is some really really really really really really really really really tha |
        | t is going to wrap to the next line                                             |
        +---------------------------------------------------------------------------------+
        ";
                println!("{}", table.render());
                assert_eq!(expected, table.render());
            }

            #[test]
            fn colored_data_works() {
                let mut table = Table::new();
                table.add_row(Row::new(vec![Cell::new("\u{1b}[31ma\u{1b}[0m")]));
                let expected = "╔═══╗
        ║ \u{1b}[31ma\u{1b}[0m ║
        ╚═══╝
        ";
                println!("{}", table.render());
                assert_eq!(expected, table.render());
            }
        */

    fn add_data_to_test_table(table: &mut Table) {
        table.add_row(
            Row::new().with_cell(
                Cell::from("This is some centered text")
                    .with_col_span(2)
                    .with_alignment(Alignment::Center),
            ),
        );

        table.add_row(
            Row::new()
                .with_cell(Cell::from("This is left aligned text"))
                .with_cell(
                    Cell::from("This is right aligned text").with_alignment(Alignment::Right),
                ),
        );

        table.add_row(
            Row::new()
                .with_cell(Cell::from("This is left aligned text"))
                .with_cell(
                    Cell::from("This is right aligned text").with_alignment(Alignment::Right),
                ),
        );

        table.add_row(
            Row::new().with_cell(
                Cell::from(
                    "This is some really really really really really \
                really really really really that is going to wrap to the next line",
                )
                .with_col_span(2),
            ),
        );

        table.add_row(
            Row::new().with_cell(
                Cell::from(
                    "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\
                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                )
                .with_col_span(2),
            ),
        );
    }
}