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
use crate::table_cell::{string_width, Alignment, TableCell};
use crate::{RowPosition, TableStyle};
use std::cmp::max;
use unicode_width::UnicodeWidthChar;

/// A set of table cells
#[derive(Debug, Clone)]
pub struct Row {
    pub cells: Vec<TableCell>,
    /// Whether the row should have a top boarder or not
    pub has_separator: bool,
}

impl Row {
    pub fn new<I, T>(cells: I) -> Row
    where
        T: Into<TableCell>,
        I: IntoIterator<Item = T>,
    {
        let mut row = Row {
            cells: vec![],
            has_separator: true,
        };

        for entry in cells.into_iter() {
            row.cells.push(entry.into());
        }

        row
    }

    pub fn empty() -> Row {
        Row {
            cells: vec![],
            has_separator: true,
        }
    }

    pub fn without_separator<I, T>(cells: I) -> Row
    where
        T: Into<TableCell>,
        I: IntoIterator<Item = T>,
    {
        let mut row = Self::new(cells);
        row.has_separator = false;
        row
    }

    /// Formats a row based on the provided table style
    pub fn format(&self, column_widths: &[usize], style: &TableStyle) -> String {
        let mut buf = String::new();

        // Since a cell can span multiple columns we need to track
        // how many columns we have actually spanned. We cannot just depend
        // on the index of the current cell when iterating
        let mut spanned_columns = 0;

        // The height of the row determined by how many times a cell had to wrap
        let mut row_height = 0;

        // Wrapped cell content
        let mut wrapped_cells = Vec::new();

        // The first thing we do is wrap the cells if their
        // content is greater than the max width of the column they are in
        for cell in &self.cells {
            let mut width = 0;
            // Iterate from 0 to the cell's col_span and add up all the max width
            // values for each column so we can properly pad the cell content later
            for j in 0..cell.col_span {
                width += column_widths[j + spanned_columns];
            }
            // Wrap to the total width - col_span to account for separators
            let wrapped_cell = cell.wrapped_content(width + cell.col_span - 1);
            row_height = max(row_height, wrapped_cell.len());
            wrapped_cells.push(wrapped_cell);
            spanned_columns += cell.col_span;
        }

        // reset spanned_columns so we can reuse it in the next loop
        spanned_columns = 0;

        // Row lines to combine into the final string at the end
        let mut lines = vec![String::new(); row_height];

        // We need to iterate over all of the column widths
        // We may not have as many cells as column widths, or the cells may not even span
        // as many columns as are in column widths. In that case weill will create empty cells
        for col_idx in 0..column_widths.len() {
            // Check to see if we actually have a cell for the column index
            // Otherwise we will just need to print out empty space as filler
            if self.cells.len() > col_idx {
                // Number of characters spanned by column
                let mut cell_span = 0;

                // Get the cell using the column index
                //
                // This is a little bit confusing because cells and columns aren't always one to one
                // We may have fewer cells than columns or some cells may span multiple columns
                // If there are fewer cells than columns we just end drawing empty cells in the else block
                // If there are fewer cells than columns but they span the total number of columns we just break out
                // of the outer for loop at the end. We know how many cells we've spanned by adding the cell's col_span to spanned_columns
                let cell = &self.cells[col_idx];
                // Calculate the cell span by adding up the widths of the columns spanned by the cell
                for c in 0..cell.col_span {
                    cell_span += column_widths[spanned_columns + c];
                }
                // Since cells can wrap we need to loop over all of the lines
                for (line_idx, line) in lines.iter_mut().enumerate().take(row_height) {
                    // Check to see if the wrapped cell has a line for the line index
                    if wrapped_cells[col_idx].len() > line_idx {
                        // We may need to pad the cell if it's contents are not as wide as some other cell in the column
                        let mut padding = 0;
                        // We need to calculate the string_width because some characters take up extra space and we need to
                        // ignore ANSI characters
                        let str_width = string_width(&wrapped_cells[col_idx][line_idx]);
                        if cell_span >= str_width {
                            padding += cell_span - str_width;
                            // If the cols_span is greater than one we need to add extra padding for the missing vertical characters
                            if cell.col_span > 1 {
                                padding += style.vertical.width().unwrap_or_default()
                                    * (cell.col_span - 1); // Subtract one since we add a vertical character to the beginning
                            }
                        }

                        // Finally we can push the string into the lines vec
                        line.push_str(
                            format!(
                                "{}{}",
                                style.vertical,
                                self.pad_string(
                                    padding,
                                    cell.alignment,
                                    &wrapped_cells[col_idx][line_idx]
                                )
                            )
                            .as_str(),
                        );
                    } else {
                        // If the cell doesn't have any content for this line just fill it with empty space
                        line.push_str(
                            format!(
                                "{}{}",
                                style.vertical,
                                str::repeat(
                                    " ",
                                    column_widths[spanned_columns] * cell.col_span + cell.col_span
                                        - 1
                                )
                            )
                            .as_str(),
                        );
                    }
                }
                // Keep track of how many columns we have actually spanned since
                // cells can be wider than a single column
                spanned_columns += cell.col_span;
            } else {
                // If we don't have a cell for the coulumn then we just create an empty one
                for line in lines.iter_mut().take(row_height) {
                    line.push_str(
                        format!(
                            "{}{}",
                            style.vertical,
                            str::repeat(" ", column_widths[spanned_columns])
                        )
                        .as_str(),
                    );
                }
                // Add one to the spanned column since the empty space is basically a cell
                spanned_columns += 1;
            }
            // If we have spanned as many columns as there are then just break out of the loop
            if spanned_columns == column_widths.len() {
                break;
            }
        }
        // Finally add all the lines together to create the row content
        for line in &lines {
            buf.push_str(line.clone().as_str());
            buf.push(style.vertical);
            buf.push('\n');
        }
        buf.pop();

        buf
    }

    /// Generates the top separator for a row.
    ///
    /// The previous seperator is used to determine junction characters
    pub fn gen_separator(
        &self,
        column_widths: &[usize],
        style: &TableStyle,
        row_position: RowPosition,
        previous_separator: Option<String>,
    ) -> String {
        let mut buf = String::new();

        // If the first cell has a col_span > 1 we need to set the next
        // intersection point to that value
        let mut next_intersection = match self.cells.first() {
            Some(cell) => cell.col_span,
            None => 1,
        };

        // Push the initial char for the row
        buf.push(style.start_for_position(row_position));

        let mut current_column = 0;

        for (i, column_width) in column_widths.iter().enumerate() {
            if i == next_intersection {
                // Draw the intersection character for the start of the column
                buf.push(style.intersect_for_position(row_position));

                current_column += 1;

                // If we still have remaining cells then we use the col_span to determine
                // when the next intersection character should be drawn
                if self.cells.len() > current_column {
                    next_intersection += self.cells[current_column].col_span;
                } else {
                    // Otherwise we just draw an intersection for every column
                    next_intersection += 1;
                }
            } else if i > 0 {
                // This means the current cell has a col_span > 1
                buf.push(style.horizontal);
            }
            // Fill in all of the horizontal space
            buf.push_str(
                str::repeat(style.horizontal.to_string().as_str(), *column_width).as_str(),
            );
        }

        buf.push(style.end_for_position(row_position));

        let mut out = String::new();

        // Merge the previous seperator string with the current buffer
        // This will handle cases where a cell above/below has a different col_span value
        match previous_separator {
            Some(prev) => {
                for pair in buf.chars().zip(prev.chars()) {
                    if pair.0 == style.outer_left_vertical || pair.0 == style.outer_right_vertical {
                        // Always take the start and end characters of the current buffer
                        out.push(pair.0);
                    } else if pair.0 != style.horizontal || pair.1 != style.horizontal {
                        out.push(style.merge_intersection_for_position(
                            pair.1,
                            pair.0,
                            row_position,
                        ));
                    } else {
                        out.push(style.horizontal);
                    }
                }
                out
            }
            None => buf,
        }
    }

    /// Returns a vector of split cell widths.
    ///
    /// A split width is the cell's total width divided by it's col_span value.
    ///
    /// Each cell's split width value is pushed into the resulting vector col_span times.
    /// Returns a vec of tuples containing the cell width and the min cell width
    pub fn split_column_widths(&self) -> Vec<(f32, usize)> {
        let mut res = Vec::new();
        for cell in &self.cells {
            let val = cell.split_width();

            let min = (cell.min_width() as f32 / cell.col_span as f32) as usize;

            let add_one = cell.min_width() as f32 % cell.col_span as f32 > 0.001;
            for i in 0..cell.col_span {
                if add_one && i == cell.col_span - 1 {
                    res.push((val + 1.0, min + 1));
                } else {
                    res.push((val, min));
                }
            }
        }

        res
    }

    /// Number of columns in the row.
    ///
    /// This is the sum of all cell's col_span values
    pub fn num_columns(&self) -> usize {
        self.cells.iter().map(|x| x.col_span).sum()
    }

    /// Pads a string accoding to the provided alignment
    fn pad_string(&self, padding: usize, alignment: Alignment, text: &str) -> String {
        match alignment {
            Alignment::Left => return format!("{}{}", text, str::repeat(" ", padding)),
            Alignment::Right => return format!("{}{}", str::repeat(" ", padding), text),
            Alignment::Center => {
                let half_padding = padding as f32 / 2.0;
                return format!(
                    "{}{}{}",
                    str::repeat(" ", half_padding.ceil() as usize),
                    text,
                    str::repeat(" ", half_padding.floor() as usize)
                );
            }
        }
    }

    /// Adds a cell to the row
    pub fn add_cell(&mut self, cell: TableCell) {
        self.cells.push(cell);
    }

}