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
use std::collections::{HashMap, HashSet};

use super::{Border, Position};

#[derive(Debug, Clone, Default)]
pub(crate) struct BordersConfig<T> {
    global: Option<T>,
    borders: Borders<T>,
    cells: BordersMap<T>,
    horizontals: HashMap<usize, HorizontalLine<T>>,
    verticals: HashMap<usize, VerticalLine<T>>,
    layout: BordersLayout,
}

impl<T: std::fmt::Debug> BordersConfig<T> {
    pub(crate) fn insert_border(&mut self, pos: Position, border: Border<T>) {
        if let Some(c) = border.top {
            self.cells.horizontal.insert(pos, c);
            self.layout.horizontals.insert(pos.0);
        }

        if let Some(c) = border.bottom {
            self.cells.horizontal.insert((pos.0 + 1, pos.1), c);
            self.layout.horizontals.insert(pos.0 + 1);
        }

        if let Some(c) = border.left {
            self.cells.vertical.insert(pos, c);
            self.layout.verticals.insert(pos.1);
        }

        if let Some(c) = border.right {
            self.cells.vertical.insert((pos.0, pos.1 + 1), c);
            self.layout.verticals.insert(pos.1 + 1);
        }

        if let Some(c) = border.left_top_corner {
            self.cells.intersection.insert((pos.0, pos.1), c);
            self.layout.horizontals.insert(pos.0);
            self.layout.verticals.insert(pos.1);
        }

        if let Some(c) = border.right_top_corner {
            self.cells.intersection.insert((pos.0, pos.1 + 1), c);
            self.layout.horizontals.insert(pos.0);
            self.layout.verticals.insert(pos.1 + 1);
        }

        if let Some(c) = border.left_bottom_corner {
            self.cells.intersection.insert((pos.0 + 1, pos.1), c);
            self.layout.horizontals.insert(pos.0 + 1);
            self.layout.verticals.insert(pos.1);
        }

        if let Some(c) = border.right_bottom_corner {
            self.cells.intersection.insert((pos.0 + 1, pos.1 + 1), c);
            self.layout.horizontals.insert(pos.0 + 1);
            self.layout.verticals.insert(pos.1 + 1);
        }
    }

    pub(crate) fn remove_border(&mut self, pos: Position, shape: (usize, usize)) {
        let (count_rows, count_cols) = shape;

        self.cells.horizontal.remove(&pos);
        self.cells.horizontal.remove(&(pos.0 + 1, pos.1));
        self.cells.vertical.remove(&pos);
        self.cells.vertical.remove(&(pos.0, pos.1 + 1));
        self.cells.intersection.remove(&pos);
        self.cells.intersection.remove(&(pos.0 + 1, pos.1));
        self.cells.intersection.remove(&(pos.0, pos.1 + 1));
        self.cells.intersection.remove(&(pos.0 + 1, pos.1 + 1));

        // clean up the layout.

        if !self.check_is_horizontal_set(pos.0, count_rows) {
            self.layout.horizontals.remove(&pos.0);
        }

        if !self.check_is_horizontal_set(pos.0 + 1, count_rows) {
            self.layout.horizontals.remove(&(pos.0 + 1));
        }

        if !self.check_is_vertical_set(pos.1, count_cols) {
            self.layout.verticals.remove(&pos.1);
        }

        if !self.check_is_vertical_set(pos.1 + 1, count_cols) {
            self.layout.verticals.remove(&(pos.1 + 1));
        }
    }

    pub(crate) fn get_border(
        &self,
        pos: Position,
        count_rows: usize,
        count_cols: usize,
    ) -> Border<&T> {
        Border {
            top: self.get_horizontal(pos, count_rows),
            bottom: self.get_horizontal((pos.0 + 1, pos.1), count_rows),
            left: self.get_vertical(pos, count_cols),
            left_top_corner: self.get_intersection(pos, count_rows, count_cols),
            left_bottom_corner: self.get_intersection((pos.0 + 1, pos.1), count_rows, count_cols),
            right: self.get_vertical((pos.0, pos.1 + 1), count_cols),
            right_top_corner: self.get_intersection((pos.0, pos.1 + 1), count_rows, count_cols),
            right_bottom_corner: self.get_intersection(
                (pos.0 + 1, pos.1 + 1),
                count_rows,
                count_cols,
            ),
        }
    }

    pub(crate) fn insert_horizontal_line(&mut self, row: usize, line: HorizontalLine<T>) {
        if line.left.is_some() {
            self.layout.left = true;
        }

        if line.right.is_some() {
            self.layout.right = true;
        }

        if line.intersection.is_some() {
            self.layout.inner_verticals = true;
        }

        self.horizontals.insert(row, line);
        self.layout.horizontals.insert(row);
    }

    pub(crate) fn get_horizontal_line(&self, row: usize) -> Option<&HorizontalLine<T>> {
        self.horizontals.get(&row)
    }

    pub(crate) fn remove_horizontal_line(&mut self, row: usize) {
        self.horizontals.remove(&row);
    }

    pub(crate) fn insert_vertical_line(&mut self, row: usize, line: VerticalLine<T>) {
        if line.top.is_some() {
            self.layout.top = true;
        }

        if line.bottom.is_some() {
            self.layout.bottom = true;
        }

        self.verticals.insert(row, line);
        self.layout.verticals.insert(row);
    }

    pub(crate) fn get_vertical_line(&self, row: usize) -> Option<&VerticalLine<T>> {
        self.verticals.get(&row)
    }

    pub(crate) fn remove_vertical_line(&mut self, row: usize) {
        self.verticals.remove(&row);
    }

    pub(crate) fn set_borders(&mut self, borders: Borders<T>) {
        self.borders = borders;
    }

    pub(crate) fn get_borders(&self) -> &Borders<T> {
        &self.borders
    }

    pub(crate) fn get_global(&self) -> Option<&T> {
        self.global.as_ref()
    }

    pub(crate) fn set_global(&mut self, value: T) {
        self.global = Some(value);
    }

    pub(crate) fn get_vertical(&self, pos: Position, count_cols: usize) -> Option<&T> {
        self.cells
            .vertical
            .get(&pos)
            .or_else(|| self.verticals.get(&pos.1).and_then(|l| l.main.as_ref()))
            .or({
                if pos.1 == count_cols {
                    self.borders.vertical_right.as_ref()
                } else if pos.1 == 0 {
                    self.borders.vertical_left.as_ref()
                } else {
                    self.borders.vertical.as_ref()
                }
            })
            .or(self.global.as_ref())
    }

    pub(crate) fn get_horizontal(&self, pos: Position, count_rows: usize) -> Option<&T> {
        self.cells
            .horizontal
            .get(&pos)
            .or_else(|| self.horizontals.get(&pos.0).and_then(|l| l.main.as_ref()))
            .or({
                if pos.0 == 0 {
                    self.borders.top.as_ref()
                } else if pos.0 == count_rows {
                    self.borders.bottom.as_ref()
                } else {
                    self.borders.horizontal.as_ref()
                }
            })
            .or(self.global.as_ref())
    }

    pub(crate) fn get_intersection(
        &self,
        pos: Position,
        count_rows: usize,
        count_cols: usize,
    ) -> Option<&T> {
        let use_top = pos.0 == 0;
        let use_bottom = pos.0 == count_rows;
        let use_left = pos.1 == 0;
        let use_right = pos.1 == count_cols;

        if let Some(c) = self.cells.intersection.get(&pos) {
            return Some(c);
        }

        let hl_c = self.horizontals.get(&pos.0).and_then(|l| {
            if use_left && l.left.is_some() {
                l.left.as_ref()
            } else if use_right && l.right.is_some() {
                l.right.as_ref()
            } else if !use_right && !use_left && l.intersection.is_some() {
                l.intersection.as_ref()
            } else {
                None
            }
        });

        if let Some(c) = hl_c {
            return Some(c);
        }

        let vl_c = self.verticals.get(&pos.1).and_then(|l| {
            if use_top && l.top.is_some() {
                l.top.as_ref()
            } else if use_bottom && l.bottom.is_some() {
                l.bottom.as_ref()
            } else if !use_top && !use_bottom && l.intersection.is_some() {
                l.intersection.as_ref()
            } else {
                None
            }
        });

        if let Some(c) = vl_c {
            return Some(c);
        }

        let borders_c = {
            if use_top && use_left {
                self.borders.top_left.as_ref()
            } else if use_top && use_right {
                self.borders.top_right.as_ref()
            } else if use_bottom && use_left {
                self.borders.bottom_left.as_ref()
            } else if use_bottom && use_right {
                self.borders.bottom_right.as_ref()
            } else if use_top {
                self.borders.top_intersection.as_ref()
            } else if use_bottom {
                self.borders.bottom_intersection.as_ref()
            } else if use_left {
                self.borders.horizontal_left.as_ref()
            } else if use_right {
                self.borders.horizontal_right.as_ref()
            } else {
                self.borders.intersection.as_ref()
            }
        };

        if let Some(c) = borders_c {
            return Some(c);
        }

        self.global.as_ref()
    }

    pub(crate) fn has_horizontal(&self, row: usize, count_rows: usize) -> bool {
        self.global.is_some()
            || (row == 0 && self.borders.has_top())
            || (row == count_rows && self.borders.has_bottom())
            || (row > 0 && row < count_rows && self.borders.has_horizontal())
            || self.is_horizontal_set(row, count_rows)
    }

    pub(crate) fn has_vertical(&self, col: usize, count_cols: usize) -> bool {
        self.global.is_some()
            || (col == 0 && self.borders.has_left())
            || (col == count_cols && self.borders.has_right())
            || (col > 0 && col < count_cols && self.borders.has_vertical())
            || self.is_vertical_set(col, count_cols)
    }

    fn is_horizontal_set(&self, row: usize, count_rows: usize) -> bool {
        (row == 0 && self.layout.top)
            || (row == count_rows && self.layout.bottom)
            || (row > 0 && row < count_rows && self.layout.inner_horizontals)
            || self.layout.horizontals.contains(&row)
    }

    fn is_vertical_set(&self, col: usize, count_cols: usize) -> bool {
        (col == 0 && self.layout.left)
            || (col == count_cols && self.layout.right)
            || (col > 0 && col < count_cols && self.layout.inner_verticals)
            || self.layout.verticals.contains(&col)
    }

    fn check_is_horizontal_set(&self, row: usize, count_rows: usize) -> bool {
        (row == 0 && self.layout.top)
            || (row == count_rows && self.layout.bottom)
            || (row > 0 && row < count_rows && self.layout.inner_horizontals)
            || self.cells.horizontal.keys().any(|&p| p.0 == row)
            || self.cells.intersection.keys().any(|&p| p.0 == row)
    }

    fn check_is_vertical_set(&self, col: usize, count_cols: usize) -> bool {
        (col == 0 && self.layout.left)
            || (col == count_cols && self.layout.right)
            || (col > 0 && col < count_cols && self.layout.inner_verticals)
            || self.cells.vertical.keys().any(|&p| p.1 == col)
            || self.cells.intersection.keys().any(|&p| p.1 == col)
    }
}

/// Borders represents a Table frame with horizontal and vertical split lines.
#[derive(Debug, Clone, Default)]
pub struct Borders<T = char> {
    /// A top horizontal on the frame.
    pub top: Option<T>,
    /// A top left on the frame.
    pub top_left: Option<T>,
    /// A top right on the frame.
    pub top_right: Option<T>,
    /// A top horizontal intersection on the frame.
    pub top_intersection: Option<T>,

    /// A bottom horizontal on the frame.
    pub bottom: Option<T>,
    /// A bottom left on the frame.
    pub bottom_left: Option<T>,
    /// A bottom right on the frame.
    pub bottom_right: Option<T>,
    /// A bottom horizontal intersection on the frame.
    pub bottom_intersection: Option<T>,

    /// A horizontal split.
    pub horizontal: Option<T>,
    /// A horizontal split on the left frame line.
    pub horizontal_left: Option<T>,
    /// A horizontal split on the right frame line.
    pub horizontal_right: Option<T>,

    /// A vertical split.
    pub vertical: Option<T>,
    /// A vertical split on the left frame line.
    pub vertical_left: Option<T>,
    /// A vertical split on the right frame line.
    pub vertical_right: Option<T>,

    /// A top left charcter on the frame.
    pub intersection: Option<T>,
}

impl<T> Borders<T> {
    /// Verifies if borders has left line set on the frame.
    pub const fn has_left(&self) -> bool {
        self.vertical_left.is_some()
            || self.horizontal_left.is_some()
            || self.top_left.is_some()
            || self.bottom_left.is_some()
    }

    /// Verifies if borders has right line set on the frame.
    pub const fn has_right(&self) -> bool {
        self.vertical_right.is_some()
            || self.horizontal_right.is_some()
            || self.top_right.is_some()
            || self.bottom_right.is_some()
    }

    /// Verifies if borders has top line set on the frame.
    pub const fn has_top(&self) -> bool {
        self.top.is_some()
            || self.top_intersection.is_some()
            || self.top_left.is_some()
            || self.top_right.is_some()
    }

    /// Verifies if borders has bottom line set on the frame.
    pub const fn has_bottom(&self) -> bool {
        self.bottom.is_some()
            || self.bottom_intersection.is_some()
            || self.bottom_left.is_some()
            || self.bottom_right.is_some()
    }

    /// Verifies if borders has horizontal lines set.
    pub const fn has_horizontal(&self) -> bool {
        self.horizontal.is_some()
            || self.horizontal_left.is_some()
            || self.horizontal_right.is_some()
            || self.intersection.is_some()
    }

    /// Verifies if borders has vertical lines set.
    pub const fn has_vertical(&self) -> bool {
        self.intersection.is_some()
            || self.vertical.is_some()
            || self.top_intersection.is_some()
            || self.bottom_intersection.is_some()
    }
}

#[derive(Debug, Clone, Default)]
pub(crate) struct BordersMap<T> {
    vertical: HashMap<Position, T>,
    horizontal: HashMap<Position, T>,
    intersection: HashMap<Position, T>,
}

#[derive(Debug, Clone, Default)]
pub(crate) struct BordersLayout {
    left: bool,
    right: bool,
    top: bool,
    bottom: bool,
    inner_verticals: bool,
    inner_horizontals: bool,
    horizontals: HashSet<usize>,
    verticals: HashSet<usize>,
}

/// A structre for a custom horizontal line.
#[derive(Debug, Clone, Copy, Default)]
pub struct HorizontalLine<T> {
    /// Line character.
    pub main: Option<T>,
    /// Line intersection character.
    pub intersection: Option<T>,
    /// Left intersection character.
    pub left: Option<T>,
    /// Right intersection character.
    pub right: Option<T>,
}

impl<T> HorizontalLine<T> {
    /// Verifies if the line has any setting set.
    pub const fn is_empty(&self) -> bool {
        self.main.is_none()
            && self.intersection.is_none()
            && self.left.is_none()
            && self.right.is_none()
    }
}

/// A structre for a vertical line.
#[derive(Debug, Clone, Copy, Default)]
pub struct VerticalLine<T> {
    /// Line character.
    pub main: Option<T>,
    /// Line intersection character.
    pub intersection: Option<T>,
    /// Left intersection character.
    pub top: Option<T>,
    /// Right intersection character.
    pub bottom: Option<T>,
}

impl<T> VerticalLine<T> {
    /// Verifies if the line has any setting set.
    pub const fn is_empty(&self) -> bool {
        self.main.is_none()
            && self.intersection.is_none()
            && self.top.is_none()
            && self.bottom.is_none()
    }
}

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

    #[test]
    fn test_insert_border() {
        let mut borders = BordersConfig::<char>::default();
        borders.insert_border((0, 0), Border::filled('x'));

        assert_eq!(borders.get_border((0, 0), 10, 10), Border::filled(&'x'));
        assert_eq!(borders.get_border((0, 0), 0, 0), Border::filled(&'x'));

        assert!(borders.is_horizontal_set(0, 10));
        assert!(borders.is_horizontal_set(1, 10));
        assert!(!borders.is_horizontal_set(2, 10));
        assert!(borders.is_vertical_set(0, 10));
        assert!(borders.is_vertical_set(1, 10));
        assert!(!borders.is_vertical_set(2, 10));

        assert!(borders.is_horizontal_set(0, 0));
        assert!(borders.is_horizontal_set(1, 0));
        assert!(!borders.is_horizontal_set(2, 0));
        assert!(borders.is_vertical_set(0, 0));
        assert!(borders.is_vertical_set(1, 0));
        assert!(!borders.is_vertical_set(2, 0));
    }

    #[test]
    fn test_insert_border_override() {
        let mut borders = BordersConfig::<char>::default();
        borders.insert_border((0, 0), Border::filled('x'));
        borders.insert_border((1, 0), Border::filled('y'));
        borders.insert_border((0, 1), Border::filled('w'));
        borders.insert_border((1, 1), Border::filled('q'));

        assert_eq!(
            borders.get_border((0, 0), 10, 10).copied(),
            Border::full('x', 'y', 'x', 'w', 'x', 'w', 'y', 'q')
        );
        assert_eq!(
            borders.get_border((0, 1), 10, 10).copied(),
            Border::full('w', 'q', 'w', 'w', 'w', 'w', 'q', 'q')
        );
        assert_eq!(
            borders.get_border((1, 0), 10, 10).copied(),
            Border::full('y', 'y', 'y', 'q', 'y', 'q', 'y', 'q')
        );
        assert_eq!(
            borders.get_border((1, 1), 10, 10).copied(),
            Border::filled('q')
        );

        assert!(borders.is_horizontal_set(0, 10));
        assert!(borders.is_horizontal_set(1, 10));
        assert!(borders.is_horizontal_set(2, 10));
        assert!(!borders.is_horizontal_set(3, 10));
        assert!(borders.is_vertical_set(0, 10));
        assert!(borders.is_vertical_set(1, 10));
        assert!(borders.is_vertical_set(2, 10));
        assert!(!borders.is_vertical_set(3, 10));
    }

    #[test]
    fn test_set_global() {
        let mut borders = BordersConfig::<char>::default();
        borders.insert_border((0, 0), Border::filled('x'));
        borders.set_global('l');

        assert_eq!(borders.get_border((0, 0), 10, 10), Border::filled(&'x'));
        assert_eq!(borders.get_border((2, 0), 10, 10), Border::filled(&'l'));

        assert!(borders.is_horizontal_set(0, 10));
        assert!(borders.is_horizontal_set(1, 10));
        assert!(!borders.is_horizontal_set(2, 10));
        assert!(borders.is_vertical_set(0, 10));
        assert!(borders.is_vertical_set(1, 10));
        assert!(!borders.is_vertical_set(2, 10));

        assert!(borders.is_horizontal_set(0, 0));
        assert!(borders.is_horizontal_set(1, 0));
        assert!(!borders.is_horizontal_set(2, 0));
        assert!(borders.is_vertical_set(0, 0));
        assert!(borders.is_vertical_set(1, 0));
        assert!(!borders.is_vertical_set(2, 0));
    }
}