oxker 0.13.0

A simple tui to view & control docker containers
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
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
use bollard::{models::ContainerSummary, secret::ContainerInspectResponse};
use core::fmt;
use parking_lot::Mutex;
use ratatui::{layout::Size, text::Text, widgets::ListState};
use std::{
    hash::Hash,
    sync::Arc,
    time::{SystemTime, UNIX_EPOCH},
};

mod container_state;

use crate::{
    ENTRY_POINT,
    app_error::AppError,
    config::Config,
    ui::{GuiState, Rerender, Status, log_sanitizer},
};
pub use container_state::*;

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum SortedOrder {
    Asc,
    Desc,
}

#[derive(Debug, Clone, Copy, Eq, Hash, PartialEq)]
pub enum Header {
    State,
    Status,
    Cpu,
    Memory,
    Id,
    Name,
    Image,
    Rx,
    Tx,
}

/// Convert Header enum into strings to display
impl fmt::Display for Header {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let disp = match self {
            Self::State => "state",
            Self::Status => "status",
            Self::Cpu => "cpu",
            Self::Memory => "memory/limit",
            Self::Id => "id",
            Self::Name => "name",
            Self::Image => "image",
            Self::Rx => "↓ rx",
            Self::Tx => "↑ tx",
        };
        write!(f, "{disp:>x$}", x = f.width().unwrap_or(1))
    }
}

#[derive(Debug, Clone, Default, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum FilterBy {
    #[default]
    Name,
    Image,
    Status,
    All,
}

/// Convert errors into strings to display
impl fmt::Display for FilterBy {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{}",
            match self {
                Self::Name => "Name",
                Self::Image => "Image",
                Self::Status => "Status",
                Self::All => "All",
            }
        )
    }
}

impl FilterBy {
    const fn next(self) -> Option<Self> {
        match self {
            Self::Name => Some(Self::Image),
            Self::Image => Some(Self::Status),
            Self::Status => Some(Self::All),
            Self::All => None,
        }
    }

    const fn prev(self) -> Option<Self> {
        match self {
            Self::Name => None,
            Self::Image => Some(Self::Name),
            Self::Status => Some(Self::Image),
            Self::All => Some(Self::Status),
        }
    }
}

#[derive(Debug, Clone)]
pub struct Filter {
    pub term: Option<String>,
    pub by: FilterBy,
}
impl Filter {
    pub fn new() -> Self {
        Self {
            term: None,
            by: FilterBy::default(),
        }
    }
}

#[derive(Debug, Clone)]
pub struct InspectData {
    pub width: usize,
    pub height: usize,
    pub as_string: String,
    pub name: String,
    pub id: ContainerId, // pub as_lines: Vec<Line<'a>>,
}

impl From<ContainerInspectResponse> for InspectData {
    fn from(input: ContainerInspectResponse) -> Self {
        let as_string = serde_json::to_string_pretty(&input)
            .unwrap_or_default()
            .lines()
            .skip(1)
            .collect::<Vec<_>>()
            .split_last()
            .map(|(_, data)| data)
            .unwrap_or_default()
            .join("\n");

        let height = as_string.lines().count();

        let mut width = 0;
        for i in as_string.lines() {
            width = width.max(i.chars().count());
        }

        Self {
            name: input.name.unwrap_or_default(),
            // TODO maybe make this an Option<Id>?
            id: ContainerId::from(input.id.unwrap_or_default().as_str()),
            width,
            height,
            as_string,
        }
    }
}

/// Global app_state, stored in an Arc<Mutex>
#[derive(Debug, Clone)]
#[cfg(not(test))]
pub struct AppData {
    containers: StatefulList<ContainerItem>,
    error: Option<AppError>,
    filter: Filter,
    hidden_containers: Vec<ContainerItem>,
    inspect_data: Option<InspectData>,
    rerender: Arc<Rerender>,
    sorted_by: Option<(Header, SortedOrder)>,
    current_sorted_id: Vec<ContainerId>,
    pub config: Config,
}

#[derive(Debug, Clone)]
#[cfg(test)]
pub struct AppData {
    pub config: Config,
    pub containers: StatefulList<ContainerItem>,
    pub error: Option<AppError>,
    pub filter: Filter,
    pub hidden_containers: Vec<ContainerItem>,
    pub inspect_data: Option<InspectData>,
    pub current_sorted_id: Vec<ContainerId>,
    pub rerender: Arc<Rerender>,
    pub sorted_by: Option<(Header, SortedOrder)>,
}

impl AppData {
    /// Generate a default app_state
    pub fn new(config: Config, redraw: &Arc<Rerender>) -> Self {
        Self {
            config,
            containers: StatefulList::new(vec![]),
            current_sorted_id: vec![],
            error: None,
            filter: Filter::new(),
            hidden_containers: vec![],
            inspect_data: None,
            rerender: Arc::clone(redraw),
            sorted_by: None,
        }
    }

    /// Current time as unix timestamp
    #[allow(clippy::expect_used)]
    fn get_systemtime() -> u64 {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("In our known reality, this error should never occur")
            .as_secs()
    }

    pub fn clear_inspect_data(&mut self) {
        self.inspect_data = None;
    }

    pub fn set_inspect_data(&mut self, data: ContainerInspectResponse) {
        self.inspect_data = Some(InspectData::from(data))
        // self.inspect_data = Some(data)
    }

    pub fn get_inspect_data(&self) -> Option<InspectData> {
        self.inspect_data.clone()
    }
    /// Filter related methods
    /// Get the filterby and filter_term
    pub const fn get_filter(&self) -> (FilterBy, Option<&String>) {
        (self.filter.by, self.filter.term.as_ref())
    }

    pub fn log_search_scroll(&mut self, np: &ScrollDirection) {
        if let Some(i) = self.get_mut_selected_container()
            && i.logs.search_scroll(np).is_some()
        {
            self.rerender.update_draw();
        }
    }

    pub fn gen_log_search(&self) -> Option<LogSearch> {
        self.get_selected_container()
            .map(|i| i.logs.gen_log_search())
    }

    /// Check if a given container can be inserted into the "visible" list, based on current filter term and filter_by
    fn can_insert(&self, container: &ContainerItem) -> bool {
        self.filter.term.as_ref().is_none_or(|term| {
            let term = term.to_lowercase();
            match self.filter.by {
                FilterBy::All => {
                    container.name.contains(&term)
                        || container.image.contains(&term)
                        || container.status.contains(&term)
                }
                FilterBy::Image => container.image.contains(&term),
                FilterBy::Name => container.name.contains(&term),
                FilterBy::Status => container.status.contains(&term),
            }
        })
    }

    /// Remove items from the containers list based on the filter term, and insert into a "hidden" vec
    /// sets the state to start if any filtering has occurred
    /// Also search in the "hidden" vec for items and insert back into the main containers vec
    fn filter_containers(&mut self) {
        self.rerender.update_draw();
        let pre_len = self.get_container_len();

        if !self.hidden_containers.is_empty() {
            let (mut new_items, tmp_items): (Vec<_>, Vec<_>) = self
                .hidden_containers
                .iter()
                .cloned()
                .partition(|item| self.can_insert(item));

            while let Some(x) = new_items.pop() {
                self.containers.items.push(x);
            }
            self.hidden_containers = tmp_items;
        }

        let (new_items, tmp_items) = self
            .containers
            .items
            .iter()
            .cloned()
            .partition(|item| self.can_insert(item));

        self.containers.items = new_items;
        self.hidden_containers.extend(tmp_items);

        self.sort_containers();
        if self.get_container_len() != pre_len {
            self.containers.start();
        }
    }

    pub fn logs_search_clear(&mut self) {
        if let Some(selected_container) = self.get_mut_selected_container() {
            selected_container.logs.search_term_clear();
            self.rerender.update_draw();
        }
    }

    /// Set a single char into the filter term
    pub fn log_search_push(&mut self, c: char) {
        let cs = self.config.log_search_case_sensitive;
        if let Some(selected_container) = self.get_mut_selected_container() {
            selected_container.logs.search_term_push(c, cs);
            self.rerender.update_draw();
        }
    }

    /// Delete the final char of the filter term
    pub fn log_search_pop(&mut self) {
        let cs = self.config.log_search_case_sensitive;
        if let Some(selected_container) = self.get_mut_selected_container() {
            selected_container.logs.search_term_pop(cs);
            self.rerender.update_draw();
        }
    }

    /// Re-filter the containers, used after the filter.by has been changed
    fn re_filter(&mut self) {
        self.containers.items.append(&mut self.hidden_containers);
        self.hidden_containers = vec![];
        self.filter_containers();
    }

    /// Set a single char into the filter term
    pub fn filter_term_push(&mut self, c: char) {
        if let Some(term) = self.filter.term.as_mut() {
            term.push(c);
        } else {
            self.filter.term = Some(format!("{c}"));
        }
        self.filter_containers();
    }

    /// Delete the final char of the filter term
    pub fn filter_term_pop(&mut self) {
        if let Some(term) = self.filter.term.as_mut() {
            // should now search for items in the tmp vec, and insert into containers if found
            term.pop();
            if term.is_empty() {
                self.filter.term = None;
            }
        }
        self.filter_containers();
    }

    /// change the filter_by option
    pub fn filter_by_next(&mut self) {
        if let Some(by) = self.filter.by.next() {
            self.filter.by = by;
            self.re_filter();
        }
    }

    /// change the filter_by option
    pub fn filter_by_prev(&mut self) {
        if let Some(by) = self.filter.by.prev() {
            self.filter.by = by;
            self.re_filter();
        }
    }

    /// Remove the filter completely
    pub fn filter_term_clear(&mut self) {
        self.filter.term = None;
        while let Some(i) = self.hidden_containers.pop() {
            if self.get_container_by_id(&i.id).is_none() {
                self.containers.items.push(i);
            }
        }
        self.sort_containers();
    }

    /// Container sort related methods
    /// Change the sorted order, also set the selected container state to match new order
    fn set_sorted(&mut self, x: Option<(Header, SortedOrder)>) {
        self.sorted_by = x;
        self.sort_containers();
        self.containers.state.select(
            self.containers
                .items
                .iter()
                .position(|i| self.get_selected_container_id().as_ref() == Some(&i.id)),
        );
        self.rerender.update_draw();
    }

    /// Remove the sorted header & order, and sort by default - created datetime
    pub fn reset_sorted(&mut self) {
        self.set_sorted(None);
        self.rerender.update_draw();
    }

    /// Sort containers based on a given header, if headings match, and already ascending, remove sorting
    pub fn set_sort_by_header(&mut self, selected_header: Header) {
        let mut output = Some((selected_header, SortedOrder::Asc));
        if let Some((current_header, order)) = self.get_sorted()
            && current_header == selected_header
        {
            match order {
                SortedOrder::Desc => output = None,
                SortedOrder::Asc => output = Some((selected_header, SortedOrder::Desc)),
            }
        }
        self.set_sorted(output);
    }

    pub const fn get_sorted(&self) -> Option<(Header, SortedOrder)> {
        self.sorted_by
    }

    /// Get a vec of the containers ID's in the order they are displayed in the containers panel
    fn get_current_ids(&self) -> Vec<ContainerId> {
        self.containers
            .items
            .iter()
            .map(|i| i.id.clone())
            .collect::<Vec<_>>()
    }
    /// Sort the containers vec, based on a heading (and if clash, then by name), either ascending or descending,
    /// If not sort set, then sort by created time
    pub fn sort_containers(&mut self) {
        if let Some((head, ord)) = self.sorted_by {
            let pre_order = self.get_current_ids();
            let sort_closure = |a: &ContainerItem, b: &ContainerItem| -> std::cmp::Ordering {
                let item_ord = match ord {
                    SortedOrder::Asc => (a, b),
                    SortedOrder::Desc => (b, a),
                };
                match head {
                    Header::State => item_ord
                        .0
                        .state
                        .order()
                        .cmp(&item_ord.1.state.order())
                        .then_with(|| item_ord.0.name.get().cmp(item_ord.1.name.get())),
                    Header::Status => item_ord
                        .0
                        .status
                        .get()
                        .cmp(item_ord.1.status.get())
                        .then_with(|| item_ord.0.name.get().cmp(item_ord.1.name.get())),
                    Header::Cpu => item_ord
                        .0
                        .cpu_stats
                        .back()
                        .cmp(&item_ord.1.cpu_stats.back())
                        .then_with(|| item_ord.0.name.get().cmp(item_ord.1.name.get())),
                    Header::Memory => item_ord
                        .0
                        .mem_stats
                        .back()
                        .cmp(&item_ord.1.mem_stats.back())
                        .then_with(|| item_ord.0.name.get().cmp(item_ord.1.name.get())),
                    Header::Id => item_ord
                        .0
                        .id
                        .cmp(&item_ord.1.id)
                        .then_with(|| item_ord.0.name.get().cmp(item_ord.1.name.get())),
                    Header::Image => item_ord
                        .0
                        .image
                        .get()
                        .cmp(item_ord.1.image.get())
                        .then_with(|| item_ord.0.name.get().cmp(item_ord.1.name.get())),
                    Header::Rx => item_ord
                        .0
                        .rx
                        .current_total()
                        .cmp(&item_ord.1.rx.current_total())
                        .then_with(|| item_ord.0.name.get().cmp(item_ord.1.name.get())),
                    Header::Tx => item_ord
                        .0
                        .tx
                        .current_total()
                        .cmp(&item_ord.1.tx.current_total())
                        .then_with(|| item_ord.0.name.get().cmp(item_ord.1.name.get())),
                    Header::Name => item_ord
                        .0
                        .name
                        .get()
                        .cmp(item_ord.1.name.get())
                        .then_with(|| item_ord.0.id.cmp(&item_ord.1.id)),
                }
            };

            self.containers.items.sort_by(sort_closure);
            if pre_order != self.get_current_ids() {
                self.rerender.update_draw();
            }
        } else if self.current_sorted_id != self.get_current_ids() {
            self.containers.items.sort_by(|a, b| {
                a.created
                    .cmp(&b.created)
                    .then_with(|| a.name.get().cmp(b.name.get()))
            });
            self.rerender.update_draw();
            self.current_sorted_id = self.get_current_ids();
        }
    }

    /// Container state methods
    /// Get the total number of none "hidden" containers
    pub const fn get_container_len(&self) -> usize {
        self.containers.items.len()
    }

    pub fn get_all_id_state(&self) -> Vec<(State, ContainerId)> {
        self.containers
            .items
            .iter()
            .map(|i| (i.state, i.id.clone()))
            .collect::<Vec<_>>()
    }

    /// Get all the ContainerItems
    /// Thnk this allow block can be removed with the 1.87 release of Clippy
    pub fn get_container_items(&self) -> &[ContainerItem] {
        &self.containers.items
    }

    /// Get title for containers section, add a suffix indicating if the containers are currently under filter
    pub fn get_container_title(&self) -> String {
        let suffix = if !self.hidden_containers.is_empty() && !self.containers.items.is_empty() {
            " - filtered"
        } else {
            ""
        };
        format!("{}{}", self.containers.get_state_title(), suffix)
    }

    /// Select the first container
    pub fn containers_start(&mut self) {
        self.containers.start();
        self.rerender.update_draw();
    }

    /// select the last container
    pub fn containers_end(&mut self) {
        self.containers.end();
        self.rerender.update_draw();
    }

    pub fn containers_scroll(&mut self, scroll: &ScrollDirection) {
        self.containers.scroll(scroll);
        self.rerender.update_draw();
    }

    /// Get ListState of containers
    pub const fn get_container_state(&mut self) -> &mut ListState {
        &mut self.containers.state
    }

    /// Get Option of the current selected container
    pub fn get_selected_container(&self) -> Option<&ContainerItem> {
        self.containers
            .state
            .selected()
            .and_then(|i| self.containers.items.get(i))
    }

    /// Find the longest port when it's transformed into a string, defaults are header lens (ip, private, public)
    ///display like this: "│   ip,   private,   public│", so (5,10,9) are the minimum lengths required
    pub fn get_longest_port(&self) -> (usize, usize, usize) {
        let mut output = (5, 10, 9);

        for item in [&self.containers.items, &self.hidden_containers] {
            for item in item {
                output.0 = output.0.max(
                    item.ports
                        .iter()
                        .map(ContainerPorts::len_ip)
                        .max()
                        .unwrap_or(output.0),
                );
                output.1 = output.1.max(
                    item.ports
                        .iter()
                        .map(ContainerPorts::len_private)
                        .max()
                        .unwrap_or(output.1),
                );
                output.2 = output.2.max(
                    item.ports
                        .iter()
                        .map(ContainerPorts::len_public)
                        .max()
                        .unwrap_or(output.2),
                );
            }
        }
        output
    }

    /// Get Option of the current selected container's ports, sorted by private port
    pub fn get_selected_ports(&self) -> Option<(Vec<ContainerPorts>, State)> {
        if let Some(item) = self.get_selected_container() {
            let mut ports = item.ports.clone();
            ports.sort_by(|a, b| a.private.cmp(&b.private));
            return Some((ports, item.state));
        }
        None
    }

    /// Get mutable Option of the current selected container
    fn get_mut_selected_container(&mut self) -> Option<&mut ContainerItem> {
        self.containers
            .state
            .selected()
            .and_then(|i| self.containers.items.get_mut(i))
    }

    /// Get a mutable container by given id
    #[cfg(not(test))]
    fn get_container_by_id(&mut self, id: &ContainerId) -> Option<&mut ContainerItem> {
        self.containers.items.iter_mut().find(|i| &i.id == id)
    }

    /// As above, but make it public to testing
    #[cfg(test)]
    pub fn get_container_by_id(&mut self, id: &ContainerId) -> Option<&mut ContainerItem> {
        self.containers.items.iter_mut().find(|i| &i.id == id)
    }

    /// Get a mutable container by given id in the tmp_container vec
    fn get_hidden_container_by_id(&mut self, id: &ContainerId) -> Option<&mut ContainerItem> {
        self.hidden_containers.iter_mut().find(|i| &i.id == id)
    }

    /// Get the ContainerName of by ID
    pub fn get_container_name_by_id(&mut self, id: &ContainerId) -> Option<&ContainerName> {
        self.containers
            .items
            .iter_mut()
            .find(|i| &i.id == id)
            .map(|i| &i.name)
    }

    /// Find the id of the currently selected container.
    /// If any containers on system, will always return a ContainerId
    /// Only returns None when no containers found.
    pub fn get_selected_container_id(&self) -> Option<ContainerId> {
        self.get_selected_container().map(|i| i.id.clone())
    }

    /// Check if a given ID matches the currently selected container
    pub fn is_selected_container(&self, id: &ContainerId) -> bool {
        self.get_selected_container().is_some_and(|i| &i.id == id)
    }

    /// Get the Id and State for the currently selected container - used by the exec check method
    pub fn get_selected_container_id_state_name(&self) -> Option<(ContainerId, State, String)> {
        self.get_selected_container()
            .map(|i| (i.id.clone(), i.state, i.name.get().to_owned()))
    }

    /// Selected DockerCommand methods
    /// Get the current selected docker command
    /// So know which command to execute
    pub fn selected_docker_controls(&self) -> Option<DockerCommand> {
        self.get_selected_container().and_then(|i| {
            i.docker_controls.state.selected().and_then(|x| {
                i.docker_controls
                    .items
                    .get(x)
                    .map(std::borrow::ToOwned::to_owned)
            })
        })
    }

    /// Change selected choice of docker commands of selected container
    pub fn docker_controls_scroll(&mut self, scroll: &ScrollDirection) {
        if let Some(i) = self.get_mut_selected_container() {
            i.docker_controls.scroll(scroll);
            // i.docker_controls.next();
            self.rerender.update_draw();
        }
    }

    /// Change selected choice of docker commands of selected container
    pub fn docker_controls_start(&mut self) {
        if let Some(i) = self.get_mut_selected_container() {
            i.docker_controls.start();
            self.rerender.update_draw();
        }
    }

    /// Change selected choice of docker commands of selected container
    pub fn docker_controls_end(&mut self) {
        if let Some(i) = self.get_mut_selected_container() {
            i.docker_controls.end();
            self.rerender.update_draw();
        }
    }

    /// Get mutable Option of the currently selected container DockerCommand state
    pub fn get_control_state(&mut self) -> Option<&mut ListState> {
        self.get_mut_selected_container()
            .map(|i| &mut i.docker_controls.state)
    }

    /// Get mutable Option of the currently selected container DockerCommand items
    pub fn get_control_items(&mut self) -> Option<&mut Vec<DockerCommand>> {
        self.get_mut_selected_container()
            .map(|i| &mut i.docker_controls.items)
    }

    /// Logs related methods
    /// Get the title for log panel for selected container, will be either
    /// 1) "logs x/x - container_name - container_image"
    /// 2) "logs - container_name - container_image" when no logs found
    /// 3) " " no container currently selected - aka no containers on system
    pub fn get_log_title(&self) -> String {
        self.get_selected_container()
            .map_or_else(String::new, |ci| {
                let logs_len = ci.logs.get_state_title();
                let prefix = if logs_len.is_empty() {
                    String::from(" ")
                } else {
                    format!("{logs_len} ")
                };
                format!("{}- {} - {}", prefix, ci.name.get(), ci.image.get())
            })
    }

    /// If scrolling horizontally along the logs, display a counter of the position in the in the scroll, `x/y`
    pub fn get_scroll_title(&mut self, width: u16) -> Option<String> {
        self.get_mut_selected_container()
            .and_then(|i| i.logs.get_scroll_title(width))
    }

    pub fn logs_horizontal_scroll(&mut self, sd: &ScrollDirection, width: u16) {
        // Change this to set a max_offset, instead of taking in width each time, then can be combined with the log_scroll beneath
        match sd {
            ScrollDirection::Down => {
                if let Some(i) = self.get_mut_selected_container() {
                    i.logs.forward(width);
                    self.rerender.update_draw();
                }
            }
            ScrollDirection::Up => {
                if let Some(i) = self.get_mut_selected_container() {
                    i.logs.back();
                    self.rerender.update_draw();
                }
            }
            // TODO set offset
            _ => (),
        }
    }

    /// select next selected log line
    pub fn log_scroll(&mut self, scroll: &ScrollDirection) {
        if let Some(i) = self.get_mut_selected_container() {
            match scroll {
                ScrollDirection::Down => i.logs.next(),
                ScrollDirection::Up => i.logs.previous(),
                // TODO set offset
                _ => (),
            }
            self.rerender.update_draw();
        }
    }

    /// select last selected log line
    pub fn log_end(&mut self) {
        if let Some(i) = self.get_mut_selected_container() {
            i.logs.end();
            self.rerender.update_draw();
        }
    }

    /// select first selected log line
    pub fn log_start(&mut self) {
        if let Some(i) = self.get_mut_selected_container() {
            i.logs.start();
            self.rerender.update_draw();
        }
    }

    /// Get mutable Vec of current containers logs
    pub fn get_logs(&self, size: Size, padding: usize) -> Vec<Text<'static>> {
        self.containers
            .state
            .selected()
            .and_then(|i| self.containers.items.get(i))
            .map_or(vec![], |i| i.logs.get_visible_logs(size, padding))
    }

    /// Get mutable Option of the currently selected container Logs state
    pub fn get_log_state(&mut self) -> Option<&mut ListState> {
        self.containers
            .state
            .selected()
            .and_then(|i| self.containers.items.get_mut(i))
            .map(|i| i.logs.state())
    }

    /// Chart data related methods
    /// Get mutable Option of the currently selected container chart data
    pub fn get_chart_data(&self) -> Option<ChartsData> {
        self.containers
            .state
            .selected()
            .and_then(|i| self.containers.items.get(i))
            .map(container_state::ContainerItem::get_chart_data)
    }

    /// Error related methods
    /// Get single app_state error
    pub fn get_error(&self) -> Option<AppError> {
        self.error.clone()
    }

    /// Remove single app_state error
    pub fn remove_error(&mut self) {
        self.error = None;
        self.rerender.update_draw();
    }

    /// Insert single app_state error
    pub fn set_error(&mut self, error: AppError, gui_state: &Arc<Mutex<GuiState>>, status: Status) {
        gui_state.lock().status_push(status);
        self.error = Some(error);
        self.rerender.update_draw();
    }

    /// Check if the selected container is a dockerised version of oxker
    /// So that can disallow commands to be send
    /// Is a shabby way of implementing this
    pub fn is_oxker(&self) -> bool {
        self.get_selected_container().is_some_and(|i| i.is_oxker)
    }

    /// Check if selected container is oxker and also that oxker is being run in a container
    pub fn is_oxker_in_container(&self) -> bool {
        self.get_selected_container()
            .is_some_and(|i| i.is_oxker && self.config.in_container)
    }

    /// Find the widths for the strings in the containers panel.
    /// So can display nicely and evenly
    /// Searches in both contains & hidden_containers
    pub fn get_width(&self) -> Columns {
        let mut columns = Columns::new();
        let count = |x: &str| u8::try_from(x.chars().count()).unwrap_or(12);

        for container in [&self.containers.items, &self.hidden_containers] {
            for container in container {
                // TODO refactor these
                let cpu_count = container.cpu_stats.back().map_or_else(
                    || count(&CpuStats::default().to_string()),
                    |i| count(&i.to_string()),
                );

                let mem_current_count = container.mem_stats.back().map_or_else(
                    || count(&ByteStats::default().to_string()),
                    |i| count(&i.to_string()),
                );
                columns.cpu.1 = columns.cpu.1.max(cpu_count);
                columns.image.1 = columns.image.1.max(count(&container.image.to_string()));
                columns.mem.1 = columns.mem.1.max(mem_current_count);
                columns.mem.2 = columns.mem.2.max(count(&container.mem_limit.to_string()));
                columns.name.1 = columns.name.1.max(count(&container.name.to_string()));
                columns.net_rx.1 = columns
                    .net_rx
                    .1
                    .max(count(&container.rx.current_total().to_string()));
                columns.net_tx.1 = columns
                    .net_tx
                    .1
                    .max(count(&container.tx.current_total().to_string()));
                columns.state.1 = columns.state.1.max(count(&container.state.to_string()));
                columns.status.1 = columns.status.1.max(count(container.status.get()));
            }
        }
        columns
    }

    /// Update related methods
    /// Get mutable reference to a container in the containers vec & the hidden_containers vec
    fn get_any_container_by_id(&mut self, id: &ContainerId) -> Option<&mut ContainerItem> {
        if self.get_hidden_container_by_id(id).is_some() {
            self.get_hidden_container_by_id(id)
        } else {
            self.get_container_by_id(id)
        }
    }

    /// Update container mem, cpu, & network stats, in single function so only need to call .lock() once
    /// Will also, if a sort is set, sort the containers
    pub fn update_stats_by_id(
        &mut self,
        id: &ContainerId,
        cpu_stat: Option<f64>,
        mem_stat: Option<u64>,
        mem_limit: u64,
        rx: u64,
        tx: u64,
    ) {
        if let Some(container) = self.get_any_container_by_id(id) {
            if container.cpu_stats.len() >= 60 {
                container.cpu_stats.pop_front();
            }
            if container.mem_stats.len() >= 60 {
                container.mem_stats.pop_front();
            }

            if let Some(cpu) = cpu_stat {
                container.cpu_stats.push_back(CpuStats::new(cpu));
            }
            if let Some(mem) = mem_stat {
                container.mem_stats.push_back(ByteStats::new(mem));
            }

            // Only insert if alive, or if is empty, need two to create an entry in the bandwidth chart, so instead this fills in the RX/TX total columns
            if container.rx.is_empty() || container.state.is_alive() {
                container.rx.push(rx);
                container.tx.push(tx);
            }

            container.mem_limit.update(mem_limit);
        }
        if self.is_selected_container(id) {
            self.rerender.update_draw();
        }
        self.sort_containers();
    }

    /// Update, or insert, containers
    pub fn update_containers(&mut self, mut all_containers: Vec<ContainerSummary>) {
        let all_ids = self
            .containers
            .items
            .iter()
            .map(|i| i.id.clone())
            .collect::<Vec<_>>();

        // Only sort it no containers currently set, as afterwards the order is fixed
        if self.containers.items.is_empty() {
            all_containers.sort_by(|a, b| a.created.cmp(&b.created));
        }

        if !all_containers.is_empty() && self.containers.state.selected().is_none() {
            self.containers.start();
        }

        for (index, id) in all_ids.iter().enumerate() {
            if !all_containers
                .iter()
                .filter_map(|i| i.id.as_ref())
                .any(|x| x == id.get())
            {
                // If removed container is currently selected, then change selected to previous
                // This will default to 0 in any edge cases
                if self.containers.state.selected().is_some() {
                    self.containers.scroll(&ScrollDirection::Up);
                }
                // Check is some, else can cause out of bounds error, if containers get removed before a docker update
                if self.containers.items.get(index).is_some() {
                    self.containers.items.remove(index);
                    if self.is_selected_container(id) {
                        self.rerender.update_draw();
                    }
                }
            }
        }

        for mut i in all_containers {
            if let Some(id) = i.id.as_ref() {
                let name = i.names.as_mut().map_or(String::new(), |names| {
                    names.first_mut().map_or(String::new(), |f| {
                        if f.starts_with('/') {
                            f.remove(0);
                        }
                        (*f).clone()
                    })
                });

                let ports = i.ports.map_or(vec![], |i| {
                    i.into_iter().map(ContainerPorts::from).collect::<Vec<_>>()
                });

                let id = ContainerId::from(id.as_str());

                let is_oxker = i
                    .command
                    .as_ref()
                    .is_some_and(|i| i.starts_with(ENTRY_POINT));

                let status = ContainerStatus::from(
                    i.status
                        .as_ref()
                        .map_or(String::new(), std::clone::Clone::clone),
                );
                let state = State::from((
                    i.state
                        .as_ref()
                        .map_or(&bollard::secret::ContainerSummaryStateEnum::DEAD, |z| z),
                    &status,
                ));
                let image = i
                    .image
                    .as_ref()
                    .map_or(String::new(), std::clone::Clone::clone);

                let created = i
                    .created
                    .map_or(0, |i| u64::try_from(i).unwrap_or_default());

                if let Some(item) = self.get_any_container_by_id(&id) {
                    if item.name.get() != name {
                        item.name.set(name);
                    }
                    if item.status != status {
                        item.status = status;
                    }
                    if item.state != state {
                        item.docker_controls.items = DockerCommand::gen_vec(state);
                        // Update the list state, needs to be None if the gen_vec returns an empty vec
                        match state {
                            State::Removing | State::Restarting | State::Unknown => {
                                item.docker_controls.state.select(None);
                            }
                            _ => item.docker_controls.start(),
                        }
                        item.state = state;
                    }

                    item.ports = ports;

                    if item.image.get() != image {
                        item.image.set(image);
                    }
                } else {
                    // container not known, so make new ContainerItem and push into containers Ve
                    let container = ContainerItem::new(
                        created, id, image, is_oxker, name, ports, state, status,
                    );
                    let can_insert = self.can_insert(&container);
                    if can_insert {
                        self.containers.items.push(container);
                    } else {
                        self.hidden_containers.push(container);
                    }
                }
            }
            // self.redraw.set_true("update_containers");
        }
    }

    /// Update logs of a given container, based on id
    pub fn update_log_by_id(&mut self, logs: Vec<String>, id: &ContainerId) {
        let color = self.config.color_logs;
        let raw = self.config.raw_logs;
        let format = self.config.timestamp_format.clone();
        let config_tz = self.config.timezone.clone();

        let cs = self.config.log_search_case_sensitive;

        let show_timestamp = self.config.show_timestamp;

        if let Some(container) = self.get_any_container_by_id(id) {
            if !container.is_oxker {
                container.last_updated = Self::get_systemtime();
                let current_len = container.logs.len();
                for mut i in logs {
                    let (log_tz, log_content) = LogsTz::splitter(i.as_str());
                    if show_timestamp {
                        i = format!(
                            "{} {}",
                            log_tz
                                .display_with_formatter(config_tz.as_ref(), &format)
                                .unwrap_or_else(|| log_tz.to_string()),
                            log_content
                        );
                    } else {
                        i = log_content;
                    }
                    let lines = if color {
                        log_sanitizer::colorize_logs(&i)
                    } else if raw {
                        log_sanitizer::raw(&i)
                    } else {
                        log_sanitizer::remove_ansi(&i)
                    };
                    container.logs.insert(Text::from(lines), log_tz, cs);
                }

                // Set the logs selected row for each container
                // Either when no long currently selected, or currently selected (before updated) is already at end
                if container.logs.state().selected().is_none()
                    || container.logs.state().selected().map_or(1, |f| f + 1) == current_len
                {
                    container.logs.end();
                }
            }
            if self.is_selected_container(id) {
                self.rerender.update_draw();
            }
        }
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {

    use super::*;
    use crate::tests::{gen_appdata, gen_container_summary, gen_containers};
    use std::collections::VecDeque;

    // ******* //
    // Sort by //
    // ******* //

    #[test]
    /// Sort by header: name
    fn test_app_data_set_sort_by_header_name() {
        let (_ids, containers) = gen_containers();

        let mut app_data = gen_appdata(&containers);

        let result = app_data.get_container_items();
        assert_eq!(result, &containers);

        // descending
        app_data.set_sorted(Some((Header::Name, SortedOrder::Desc)));
        let result = app_data.get_container_items();
        let (a, b, c) = (&result[0], &result[1], &result[2]);
        assert_eq!(a.id, ContainerId::from("3"));
        assert_eq!(b.id, ContainerId::from("2"));
        assert_eq!(c.id, ContainerId::from("1"));

        // ascending
        app_data.set_sorted(Some((Header::Name, SortedOrder::Asc)));
        let result = app_data.get_container_items();
        let (a, b, c) = (&result[0], &result[1], &result[2]);
        assert_eq!(a.id, ContainerId::from("1"));
        assert_eq!(b.id, ContainerId::from("2"));
        assert_eq!(c.id, ContainerId::from("3"));
    }

    #[test]
    /// Sort by header: state
    fn test_app_data_set_sort_by_header_state() {
        let (_ids, containers) = gen_containers();

        let mut app_data = gen_appdata(&containers);

        let result = app_data.get_container_items();
        assert_eq!(result, &containers);

        if let Some(i) = app_data.get_container_by_id(&ContainerId::from("1")) {
            i.state = State::Exited;
        }
        if let Some(i) = app_data.get_container_by_id(&ContainerId::from("2")) {
            i.state = State::Running(RunningState::Healthy);
        }
        if let Some(i) = app_data.get_container_by_id(&ContainerId::from("3")) {
            i.state = State::Paused;
        }

        // descending
        app_data.set_sorted(Some((Header::State, SortedOrder::Desc)));
        let result = app_data.get_container_items();
        let (a, b, c) = (&result[0], &result[1], &result[2]);
        assert_eq!(a.id, ContainerId::from("1"));
        assert_eq!(b.id, ContainerId::from("3"));
        assert_eq!(c.id, ContainerId::from("2"));

        // ascending
        app_data.set_sorted(Some((Header::State, SortedOrder::Asc)));
        let result = app_data.get_container_items();
        let (a, b, c) = (&result[0], &result[1], &result[2]);
        assert_eq!(a.id, ContainerId::from("2"));
        assert_eq!(b.id, ContainerId::from("3"));
        assert_eq!(c.id, ContainerId::from("1"));
    }

    #[test]
    /// Sort by header: status
    fn test_app_data_set_sort_by_header_status() {
        let (_ids, containers) = gen_containers();

        let mut app_data = gen_appdata(&containers);

        let result = app_data.get_container_items();
        assert_eq!(result, &containers);

        if let Some(i) = app_data.get_container_by_id(&ContainerId::from("2")) {
            ContainerStatus::from("Exited (0) 10 minutes ago".to_owned()).clone_into(&mut i.status);
        }

        if let Some(i) = app_data.get_container_by_id(&ContainerId::from("3")) {
            // "Up 2 hours (Paused)".clone_into(&mut i.status);
            ContainerStatus::from("Up 2 hours (Paused)".to_owned()).clone_into(&mut i.status);
        }

        // Sort by status
        // descending
        app_data.set_sorted(Some((Header::Status, SortedOrder::Desc)));
        let result = app_data.get_container_items();
        let (a, b, c) = (&result[0], &result[1], &result[2]);
        assert_eq!(a.id, ContainerId::from("3"));
        assert_eq!(b.id, ContainerId::from("1"));
        assert_eq!(c.id, ContainerId::from("2"));

        // ascending
        app_data.set_sorted(Some((Header::Status, SortedOrder::Asc)));
        let result = app_data.get_container_items();
        let (a, b, c) = (&result[0], &result[1], &result[2]);
        assert_eq!(a.id, ContainerId::from("2"));
        assert_eq!(b.id, ContainerId::from("1"));
        assert_eq!(c.id, ContainerId::from("3"));
    }

    #[test]
    /// Sort by header: cpu
    fn test_app_data_set_sort_by_header_cpu() {
        let (_ids, containers) = gen_containers();

        let mut app_data = gen_appdata(&containers);

        let result = app_data.get_container_items();
        assert_eq!(result, &containers);

        if let Some(i) = app_data.get_container_by_id(&ContainerId::from("1")) {
            i.cpu_stats = VecDeque::from([CpuStats::new(10.1)]);
        }
        if let Some(i) = app_data.get_container_by_id(&ContainerId::from("2")) {
            i.cpu_stats = VecDeque::from([CpuStats::new(8.1)]);
        }
        if let Some(i) = app_data.get_container_by_id(&ContainerId::from("3")) {
            i.cpu_stats = VecDeque::from([CpuStats::new(20.3)]);
        }

        // descending
        app_data.set_sorted(Some((Header::Cpu, SortedOrder::Desc)));
        let result = app_data.get_container_items();
        let (a, b, c) = (&result[0], &result[1], &result[2]);
        assert_eq!(a.id, ContainerId::from("3"));
        assert_eq!(b.id, ContainerId::from("1"));
        assert_eq!(c.id, ContainerId::from("2"));

        // ascending
        app_data.set_sorted(Some((Header::Cpu, SortedOrder::Asc)));
        let result = app_data.get_container_items();
        let (a, b, c) = (&result[0], &result[1], &result[2]);
        assert_eq!(a.id, ContainerId::from("2"));
        assert_eq!(b.id, ContainerId::from("1"));
        assert_eq!(c.id, ContainerId::from("3"));
    }

    #[test]
    /// Sort by header: memory
    fn test_app_data_set_sort_by_header_mem() {
        let (_ids, containers) = gen_containers();

        let mut app_data = gen_appdata(&containers);

        let result = app_data.get_container_items();
        assert_eq!(result, &containers);

        if let Some(i) = app_data.get_container_by_id(&ContainerId::from("1")) {
            i.mem_stats = VecDeque::from([ByteStats::new(40)]);
        }
        if let Some(i) = app_data.get_container_by_id(&ContainerId::from("2")) {
            i.mem_stats = VecDeque::from([ByteStats::new(80)]);
        }
        if let Some(i) = app_data.get_container_by_id(&ContainerId::from("3")) {
            i.mem_stats = VecDeque::from([ByteStats::new(2)]);
        }

        // descending
        app_data.set_sorted(Some((Header::Memory, SortedOrder::Desc)));
        let result = app_data.get_container_items();
        let (a, b, c) = (&result[0], &result[1], &result[2]);
        assert_eq!(a.id, ContainerId::from("2"));
        assert_eq!(b.id, ContainerId::from("1"));
        assert_eq!(c.id, ContainerId::from("3"));

        // ascending
        app_data.set_sorted(Some((Header::Memory, SortedOrder::Asc)));
        let result = app_data.get_container_items();
        let (a, b, c) = (&result[0], &result[1], &result[2]);
        assert_eq!(a.id, ContainerId::from("3"));
        assert_eq!(b.id, ContainerId::from("1"));
        assert_eq!(c.id, ContainerId::from("2"));
    }

    #[test]
    /// Sort by header: id
    fn test_app_data_set_sort_by_header_id() {
        let (_ids, containers) = gen_containers();

        let mut app_data = gen_appdata(&containers);

        let result = app_data.get_container_items();
        assert_eq!(result, &containers);

        // descending
        app_data.set_sorted(Some((Header::Id, SortedOrder::Desc)));
        let result = app_data.get_container_items();
        let (a, b, c) = (&result[0], &result[1], &result[2]);
        assert_eq!(a.id, ContainerId::from("3"));
        assert_eq!(b.id, ContainerId::from("2"));
        assert_eq!(c.id, ContainerId::from("1"));

        // ascending
        app_data.set_sorted(Some((Header::Id, SortedOrder::Asc)));
        let result = app_data.get_container_items();
        let (a, b, c) = (&result[0], &result[1], &result[2]);
        assert_eq!(a.id, ContainerId::from("1"));
        assert_eq!(b.id, ContainerId::from("2"));
        assert_eq!(c.id, ContainerId::from("3"));
    }

    #[test]
    /// Sort by header: image
    fn test_app_data_set_sort_by_header_image() {
        let (_ids, containers) = gen_containers();

        let mut app_data = gen_appdata(&containers);

        let result = app_data.get_container_items();
        assert_eq!(result, &containers);

        // descending
        app_data.set_sorted(Some((Header::Image, SortedOrder::Desc)));
        let result = app_data.get_container_items();
        let (a, b, c) = (&result[0], &result[1], &result[2]);
        assert_eq!(a.id, ContainerId::from("3"));
        assert_eq!(b.id, ContainerId::from("2"));
        assert_eq!(c.id, ContainerId::from("1"));

        // ascending
        app_data.set_sorted(Some((Header::Image, SortedOrder::Asc)));
        let result = app_data.get_container_items();
        let (a, b, c) = (&result[0], &result[1], &result[2]);
        assert_eq!(a.id, ContainerId::from("1"));
        assert_eq!(b.id, ContainerId::from("2"));
        assert_eq!(c.id, ContainerId::from("3"));
    }

    #[test]
    /// Sort by header: rx
    fn test_app_data_set_sort_by_header_rx() {
        let (_ids, containers) = gen_containers();

        let mut app_data = gen_appdata(&containers);

        let result = app_data.get_container_items();
        assert_eq!(result, &containers);

        if let Some(i) = app_data.get_container_by_id(&ContainerId::from("1")) {
            i.rx = NetworkBandwidth::new();
            i.rx.push(40);
        }
        if let Some(i) = app_data.get_container_by_id(&ContainerId::from("2")) {
            i.rx = NetworkBandwidth::new();
            i.rx.push(80);
        }
        if let Some(i) = app_data.get_container_by_id(&ContainerId::from("3")) {
            i.rx = NetworkBandwidth::new();
            i.rx.push(2);
        }

        // descending
        app_data.set_sorted(Some((Header::Rx, SortedOrder::Desc)));
        let result = app_data.get_container_items();
        let (a, b, c) = (&result[0], &result[1], &result[2]);
        assert_eq!(a.id, ContainerId::from("2"));
        assert_eq!(b.id, ContainerId::from("1"));
        assert_eq!(c.id, ContainerId::from("3"));

        // ascending
        app_data.set_sorted(Some((Header::Rx, SortedOrder::Asc)));
        let result = app_data.get_container_items();
        let (a, b, c) = (&result[0], &result[1], &result[2]);
        assert_eq!(a.id, ContainerId::from("3"));
        assert_eq!(b.id, ContainerId::from("1"));
        assert_eq!(c.id, ContainerId::from("2"));
    }

    #[test]
    /// Sort by header: tx
    fn test_app_data_set_sort_by_header_tx() {
        let (_ids, containers) = gen_containers();

        let mut app_data = gen_appdata(&containers);

        let result = app_data.get_container_items();
        assert_eq!(result, &containers);

        if let Some(i) = app_data.get_container_by_id(&ContainerId::from("1")) {
            i.rx = NetworkBandwidth::new();
            i.rx.push(400);
        }
        if let Some(i) = app_data.get_container_by_id(&ContainerId::from("2")) {
            i.rx = NetworkBandwidth::new();
            i.rx.push(80);
        }
        if let Some(i) = app_data.get_container_by_id(&ContainerId::from("3")) {
            i.rx = NetworkBandwidth::new();
            i.rx.push(83);
        }

        // descending
        app_data.set_sorted(Some((Header::Rx, SortedOrder::Desc)));
        let result = app_data.get_container_items();
        let (a, b, c) = (&result[0], &result[1], &result[2]);
        assert_eq!(a.id, ContainerId::from("1"));
        assert_eq!(b.id, ContainerId::from("3"));
        assert_eq!(c.id, ContainerId::from("2"));

        // ascending
        app_data.set_sorted(Some((Header::Rx, SortedOrder::Asc)));
        let result = app_data.get_container_items();
        let (a, b, c) = (&result[0], &result[1], &result[2]);
        assert_eq!(a.id, ContainerId::from("2"));
        assert_eq!(b.id, ContainerId::from("3"));
        assert_eq!(c.id, ContainerId::from("1"));
    }

    #[test]
    /// Sort by header when selected headers match
    fn test_app_data_set_sort_by_header_match() {
        let (_ids, containers) = gen_containers();

        let mut app_data = gen_appdata(&containers);

        let result = app_data.get_container_items();
        assert_eq!(result, &containers);

        // descending
        app_data.set_sorted(Some((Header::Rx, SortedOrder::Desc)));
        let result = app_data.get_container_items();
        let (a, b, c) = (&result[0], &result[1], &result[2]);
        assert_eq!(a.id, ContainerId::from("3"));
        assert_eq!(b.id, ContainerId::from("2"));
        assert_eq!(c.id, ContainerId::from("1"));

        // ascending
        app_data.set_sorted(Some((Header::Rx, SortedOrder::Asc)));
        let result = app_data.get_container_items();
        let (a, b, c) = (&result[0], &result[1], &result[2]);
        assert_eq!(a.id, ContainerId::from("1"));
        assert_eq!(b.id, ContainerId::from("2"));
        assert_eq!(c.id, ContainerId::from("3"));
    }

    #[test]
    /// reset sorted
    fn test_app_data_reset_sorted() {
        let (_ids, containers) = gen_containers();

        let mut app_data = gen_appdata(&containers);

        let result = app_data.get_container_items();
        assert_eq!(result, &containers);

        if let Some(i) = app_data.get_container_by_id(&ContainerId::from("1")) {
            i.rx = NetworkBandwidth::new();
            i.rx.push(400);
        }
        if let Some(i) = app_data.get_container_by_id(&ContainerId::from("2")) {
            i.rx = NetworkBandwidth::new();
            i.rx.push(80);
        }
        if let Some(i) = app_data.get_container_by_id(&ContainerId::from("3")) {
            i.rx = NetworkBandwidth::new();
            i.rx.push(83);
        }

        app_data.set_sorted(Some((Header::Rx, SortedOrder::Asc)));
        let result = app_data.get_container_items();
        let (a, b, c) = (&result[0], &result[1], &result[2]);
        assert_eq!(a.id, ContainerId::from("2"));
        assert_eq!(b.id, ContainerId::from("3"));
        assert_eq!(c.id, ContainerId::from("1"));

        app_data.set_sorted(None);
        let result = app_data.get_container_items();
        let (a, b, c) = (&result[0], &result[1], &result[2]);
        assert_eq!(a.id, ContainerId::from("1"));
        assert_eq!(b.id, ContainerId::from("2"));
        assert_eq!(c.id, ContainerId::from("3"));
    }

    // **************** //
    // Container state  //
    // **************** //

    #[test]
    /// Get len of current containers vec
    fn test_app_data_get_container_len() {
        let (_ids, containers) = gen_containers();
        let app_data = gen_appdata(&containers);
        assert_eq!(app_data.get_container_len(), 3);
    }

    #[test]
    /// Select the first container
    fn test_app_data_containers_start() {
        let (_ids, containers) = gen_containers();
        let mut app_data = gen_appdata(&containers);

        // No container selected
        let result = app_data.get_container_state();
        assert_eq!(result.selected(), None);
        assert_eq!(result.offset(), 0);

        // First container selected
        app_data.containers_start();
        let result = app_data.get_container_state();
        assert_eq!(result.selected(), Some(0));
        assert_eq!(result.offset(), 0);

        let result = app_data.get_selected_container_id();
        assert_eq!(result, Some(ContainerId::from("1")));
        let result = app_data.get_selected_container_id_state_name();
        assert_eq!(
            result,
            Some((
                ContainerId::from("1"),
                State::Running(RunningState::Healthy),
                "container_1".to_owned()
            ))
        );

        // Calling previous when at start has no effect
        app_data.containers_scroll(&ScrollDirection::Up);
        let result = app_data.get_selected_container_id();
        assert_eq!(result, Some(ContainerId::from("1")));
        let result = app_data.get_selected_container_id_state_name();
        assert_eq!(
            result,
            Some((
                ContainerId::from("1"),
                State::Running(RunningState::Healthy),
                "container_1".to_owned()
            ))
        );
    }

    #[test]
    /// advance container list state by one
    /// get get_selected_container_id() & get_selected_container_id_state_name() return valid Some data
    fn test_app_data_containers_next() {
        let (_ids, containers) = gen_containers();
        let mut app_data = gen_appdata(&containers);

        // Advance list state by 1
        app_data.containers_start();
        app_data.containers.scroll(&ScrollDirection::Down);

        let result = app_data.get_container_state();
        assert_eq!(result.selected(), Some(1));
        assert_eq!(result.offset(), 0);

        let result = app_data.get_selected_container_id();
        assert_eq!(result, Some(ContainerId::from("2")));
        let result = app_data.get_selected_container_id_state_name();
        assert_eq!(
            result,
            Some((
                ContainerId::from("2"),
                State::Running(RunningState::Healthy),
                "container_2".to_owned()
            ))
        );
    }

    #[test]
    /// advance container list state to the end
    /// get get_selected_container_id() & get_selected_container_id_state_name() return valid Some data
    fn test_app_data_containers_end() {
        let (_ids, containers) = gen_containers();
        let mut app_data = gen_appdata(&containers);

        app_data.containers_end();
        let result = app_data.get_container_state();
        assert_eq!(result.selected(), Some(2));
        assert_eq!(result.offset(), 0);

        let result = app_data.get_selected_container_id();
        assert_eq!(result, Some(ContainerId::from("3")));
        let result = app_data.get_selected_container_id_state_name();
        assert_eq!(
            result,
            Some((
                ContainerId::from("3"),
                State::Running(RunningState::Healthy),
                "container_3".to_owned()
            ))
        );

        // Calling previous when at end has no effect
        app_data.containers.scroll(&ScrollDirection::Down);
        let result = app_data.get_selected_container_id();
        assert_eq!(result, Some(ContainerId::from("3")));
        let result = app_data.get_selected_container_id_state_name();
        assert_eq!(
            result,
            Some((
                ContainerId::from("3"),
                State::Running(RunningState::Healthy),
                "container_3".to_owned()
            ))
        );
    }

    #[test]
    /// go to previous container
    fn test_app_data_containers_prev() {
        let (_ids, containers) = gen_containers();
        let mut app_data = gen_appdata(&containers);

        app_data.containers_end();
        app_data.containers.scroll(&ScrollDirection::Up);
        let result = app_data.get_container_state();
        assert_eq!(result.selected(), Some(1));
        assert_eq!(result.offset(), 0);
    }

    #[test]
    /// Get the currently selected container
    fn test_app_data_get_selected_container() {
        let (_ids, mut containers) = gen_containers();
        let mut app_data = gen_appdata(&containers);

        let result = app_data.get_selected_container();
        assert_eq!(result, None);

        app_data.containers.start();
        app_data.containers.scroll(&ScrollDirection::Down);

        let result = app_data.get_selected_container();
        assert_eq!(result, Some(&containers[1]));

        // As above, but now as mut
        let result = app_data.get_mut_selected_container();
        assert_eq!(result, Some(&mut containers[1]));
    }

    #[test]
    /// Get mut container by id
    fn test_app_data_get_container_by_id() {
        let (_ids, mut containers) = gen_containers();
        let mut app_data = gen_appdata(&containers);

        let result = app_data.get_container_by_id(&ContainerId::from("2"));
        assert_eq!(result, Some(&mut containers[1]));
    }

    #[test]
    /// Get just the containers name by id
    fn test_app_data_get_container_name_by_id() {
        let (_ids, containers) = gen_containers();
        let mut app_data = gen_appdata(&containers);

        let result = app_data.get_container_name_by_id(&ContainerId::from("2"));
        assert_eq!(result, Some(&ContainerName::from("container_2")));
    }

    #[test]
    /// Get the id of the currently selected container
    fn test_app_data_get_selected_container_id() {
        let (_ids, containers) = gen_containers();
        let mut app_data = gen_appdata(&containers);
        app_data.containers_end();

        let result = app_data.get_selected_container_id();
        assert_eq!(result, Some(ContainerId::from("3")));
    }

    #[test]
    fn test_app_data_get_selected_container_id_state_name() {
        let (_ids, containers) = gen_containers();
        let mut app_data = gen_appdata(&containers);
        app_data.containers_end();

        let result = app_data.get_selected_container_id_state_name();
        assert_eq!(
            result,
            Some((
                ContainerId::from("3"),
                State::Running(RunningState::Healthy),
                "container_3".to_owned()
            ))
        );
    }

    // ************** //
    // DockerControls //
    // ************** //

    #[test]
    /// Docker commands returned correctly
    fn test_app_data_selected_docker_command() {
        let (_ids, containers) = gen_containers();
        let mut app_data = gen_appdata(&containers);

        // No commands when no container selected
        let result = app_data.selected_docker_controls();
        assert!(result.is_none());

        // Correct commands returned
        app_data.containers_start();
        app_data.docker_controls_start();

        let result = app_data.selected_docker_controls();
        assert_eq!(result, Some(DockerCommand::Pause));
    }

    #[test]
    /// Docker command next works
    fn test_app_data_selected_docker_command_next() {
        let (_ids, containers) = gen_containers();
        let mut app_data = gen_appdata(&containers);
        app_data.containers_start();
        app_data.docker_controls_start();
        app_data.docker_controls_scroll(&ScrollDirection::Down);

        let result = app_data.selected_docker_controls();
        assert_eq!(result, Some(DockerCommand::Restart));
    }

    #[test]
    /// Dockercommand end works, and next has no effect when at end
    fn test_app_data_selected_docker_command_end() {
        let (_ids, containers) = gen_containers();
        let mut app_data = gen_appdata(&containers);
        app_data.containers_start();
        app_data.docker_controls_end();

        let result = app_data.selected_docker_controls();
        assert_eq!(result, Some(DockerCommand::Delete));

        // Next has no effect when at end
        app_data.docker_controls_scroll(&ScrollDirection::Down);
        let result = app_data.selected_docker_controls();
        assert_eq!(result, Some(DockerCommand::Delete));
    }

    #[test]
    /// Docker commands previous works, and has no effect when at start
    fn test_app_data_selected_docker_command_previous() {
        let (_ids, containers) = gen_containers();
        let mut app_data = gen_appdata(&containers);
        app_data.containers_start();
        app_data.docker_controls_end();
        app_data.docker_controls_scroll(&ScrollDirection::Up);

        let result = app_data.selected_docker_controls();
        assert_eq!(result, Some(DockerCommand::Stop));

        // previous has no effect when at start
        app_data.docker_controls_start();
        app_data.docker_controls_scroll(&ScrollDirection::Up);
        let result = app_data.selected_docker_controls();
        assert_eq!(result, Some(DockerCommand::Pause));
    }

    #[test]
    /// DockerCommands get correct controls dependant on container state
    fn test_app_data_get_control_items() {
        let test_state = |state: State, expected: &mut Vec<DockerCommand>| {
            let gen_item_state = |state: State| {
                ContainerItem::new(
                    1,
                    ContainerId::from("1"),
                    "image_1".to_owned(),
                    false,
                    "container_1".to_owned(),
                    vec![],
                    state,
                    ContainerStatus::from("Up 1 hour".to_owned()),
                )
            };
            let mut app_data = gen_appdata(&[gen_item_state(state)]);
            app_data.containers_start();
            app_data.docker_controls_start();

            let result = app_data.get_control_items();
            assert_eq!(result, Some(expected));
        };

        test_state(
            State::Dead,
            &mut vec![
                DockerCommand::Start,
                DockerCommand::Restart,
                DockerCommand::Delete,
            ],
        );
        test_state(
            State::Exited,
            &mut vec![
                DockerCommand::Start,
                DockerCommand::Restart,
                DockerCommand::Delete,
            ],
        );
        test_state(
            State::Paused,
            &mut vec![
                DockerCommand::Resume,
                DockerCommand::Stop,
                DockerCommand::Delete,
            ],
        );
        test_state(State::Removing, &mut vec![DockerCommand::Delete]);
        test_state(
            State::Restarting,
            &mut vec![DockerCommand::Stop, DockerCommand::Delete],
        );
        test_state(
            State::Running(RunningState::Healthy),
            &mut vec![
                DockerCommand::Pause,
                DockerCommand::Restart,
                DockerCommand::Stop,
                DockerCommand::Delete,
            ],
        );
        test_state(State::Unknown, &mut vec![DockerCommand::Delete]);
    }

    // ****** //
    // Filter //
    // ****** //

    #[test]
    /// Data is filtered correctly by name
    fn test_app_data_filter_by_name() {
        let (_, containers) = gen_containers();

        let mut app_data = gen_appdata(&containers);

        assert!(app_data.get_filter().1.is_none());

        let pre_len = app_data.containers.items.len();
        app_data.filter_term_push('_');
        app_data.filter_term_push('2');

        assert_eq!(app_data.get_filter().1, Some(&"_2".to_string()));

        app_data.filter_containers();
        let post_len = app_data.containers.items.len();
        assert!(pre_len != post_len);
        assert_eq!(post_len, 1);

        // Can insert checks against the current filter term
        assert!(app_data.can_insert(&containers[1]));
        assert!(!app_data.can_insert(&containers[0]));
        assert!(!app_data.can_insert(&containers[2]));
    }

    #[test]
    /// Data is filtered correctly by image
    fn test_app_data_filter_by_image() {
        let (_, containers) = gen_containers();

        let mut app_data = gen_appdata(&containers);

        assert!(app_data.get_filter().1.is_none());

        let pre_len = app_data.containers.items.len();
        for c in ['i', 'm', 'a', 'g', 'e', '_', '2'] {
            app_data.filter_term_push(c);
        }
        // app_data.filter_term_push('2');
        app_data.filter_by_next();

        assert_eq!(
            app_data.get_filter(),
            (FilterBy::Image, Some(&"image_2".to_string()))
        );

        app_data.filter_containers();
        let post_len = app_data.containers.items.len();
        assert!(pre_len != post_len);
        assert_eq!(post_len, 1);

        assert!(!app_data.can_insert(&containers[0]));
        assert!(app_data.can_insert(&containers[1]));
        assert!(!app_data.can_insert(&containers[2]));
    }

    #[test]
    /// Data is filtered correctly by status
    fn test_app_data_filter_by_status() {
        let (_, mut containers) = gen_containers();
        ContainerStatus::from("Exited".to_owned()).clone_into(&mut containers[0].status);
        let mut app_data = gen_appdata(&containers);

        assert!(app_data.get_filter().1.is_none());

        let pre_len = app_data.containers.items.len();
        app_data.filter_term_push('x');

        app_data.filter_by_next();
        app_data.filter_by_next();

        assert_eq!(
            app_data.get_filter(),
            (FilterBy::Status, Some(&"x".to_string()))
        );

        app_data.filter_containers();
        let post_len = app_data.containers.items.len();
        assert!(pre_len != post_len);
        assert_eq!(post_len, 1);

        assert!(app_data.can_insert(&containers[0]));
        assert!(!app_data.can_insert(&containers[1]));
        assert!(!app_data.can_insert(&containers[2]));
    }

    #[test]
    /// Data is filtered correctly by all
    fn test_app_data_filter_by_all() {
        let (_, mut containers) = gen_containers();
        ContainerStatus::from("Exited".to_owned()).clone_into(&mut containers[0].status);
        let mut app_data = gen_appdata(&containers);

        assert!(app_data.get_filter().1.is_none());

        let pre_len = app_data.containers.items.len();
        app_data.filter_term_push('x');

        app_data.filter_by_next();
        app_data.filter_by_next();
        app_data.filter_by_next();

        assert_eq!(
            app_data.get_filter(),
            (FilterBy::All, Some(&"x".to_string()))
        );

        app_data.filter_containers();
        let post_len = app_data.containers.items.len();
        assert!(pre_len != post_len);
        assert_eq!(post_len, 1);

        assert!(app_data.can_insert(&containers[0]));
        assert!(!app_data.can_insert(&containers[1]));
        assert!(!app_data.can_insert(&containers[2]));
    }

    #[test]
    /// Data is filtered correctly after various next() and previous() commands
    fn test_app_data_filter_prev() {
        let (_, mut containers) = gen_containers();
        ContainerStatus::from("Exited".to_owned()).clone_into(&mut containers[0].status);
        let mut app_data = gen_appdata(&containers);

        assert!(app_data.get_filter().1.is_none());

        let pre_len = app_data.containers.items.len();
        app_data.filter_term_push('x');

        app_data.filter_by_next();
        app_data.filter_by_next();

        assert_eq!(
            app_data.get_filter(),
            (FilterBy::Status, Some(&"x".to_string()))
        );

        app_data.filter_containers();
        let post_len = app_data.containers.items.len();
        assert!(pre_len != post_len);
        assert_eq!(post_len, 1);

        assert!(app_data.can_insert(&containers[0]));
        assert!(!app_data.can_insert(&containers[1]));
        assert!(!app_data.can_insert(&containers[2]));

        app_data.filter_by_prev();
        assert_eq!(
            app_data.get_filter(),
            (FilterBy::Image, Some(&"x".to_string()))
        );

        app_data.filter_containers();
        let post_len = app_data.containers.items.len();
        assert!(pre_len != post_len);
        assert_eq!(post_len, 0);

        assert!(!app_data.can_insert(&containers[0]));
        assert!(!app_data.can_insert(&containers[1]));
        assert!(!app_data.can_insert(&containers[2]));
    }

    // **** //
    // Logs //
    // **** //

    #[test]
    /// log title string generated correctly
    fn test_app_data_get_log_title() {
        let (ids, containers) = gen_containers();

        let mut app_data = gen_appdata(&containers);

        // No container selected select
        let result = app_data.get_log_title();
        assert_eq!(result, "");

        // No logs
        app_data.containers.start();
        let result = app_data.get_log_title();
        assert_eq!(result, " - container_1 - image_1");

        // On last line of logs
        let logs = (1..=3).map(|i| format!("{i} {i}")).collect::<Vec<_>>();
        app_data.update_log_by_id(logs, &ids[0]);
        let result = app_data.get_log_title();
        assert_eq!(result, " 3/3 - container_1 - image_1");

        // Change log state to no longer be at the end
        app_data.log_scroll(&ScrollDirection::Up);
        let result = app_data.get_log_title();
        assert_eq!(result, " 2/3 - container_1 - image_1");
    }

    #[test]
    /// log title string generated correctly after container change
    fn test_app_data_get_log_title_after_container_change() {
        let (ids, containers) = gen_containers();
        let mut app_data = gen_appdata(&containers);

        // No container selected select
        let result = app_data.get_log_title();
        assert_eq!(result, "");

        app_data.containers_start();

        let result = app_data.get_log_title();
        assert_eq!(result, " - container_1 - image_1");

        // change container
        app_data.containers_scroll(&ScrollDirection::Down);
        let result = app_data.get_log_title();
        assert_eq!(result, " - container_2 - image_2");

        // On last line of logs
        let logs = (1..=3).map(|i| format!("{i} {i}")).collect::<Vec<_>>();
        app_data.update_log_by_id(logs, &ids[1]);
        let result = app_data.get_log_title();
        assert_eq!(result, " 3/3 - container_2 - image_2");

        // Change log state to no longer be at the end
        app_data.log_scroll(&ScrollDirection::Up);
        let result = app_data.get_log_title();
        assert_eq!(result, " 2/3 - container_2 - image_2");
    }

    #[test]
    /// update logs by id works
    fn test_app_data_update_log_by_id() {
        let (ids, containers) = gen_containers();
        let mut app_data = gen_appdata(&containers);

        // No container selected select
        let result = app_data.get_log_title();
        assert_eq!(result, "");

        app_data.containers_start();
        let logs = (1..=3).map(|i| format!("{i} {i}")).collect::<Vec<_>>();

        app_data.update_log_by_id(logs, &ids[0]);

        let result = app_data.get_log_state();
        assert!(result.is_some());
        assert_eq!(result.as_ref().unwrap().selected(), Some(2));
        assert_eq!(result.unwrap().offset(), 0);

        let result = app_data.get_logs(
            Size {
                width: 20,
                height: 4,
            },
            1,
        );
        assert_eq!(result.len(), 3);

        let result = app_data.get_log_title();
        assert_eq!(result, " 3/3 - container_1 - image_1");
    }

    #[test]
    /// logs state reset to start
    fn test_app_data_logs_start() {
        let (ids, containers) = gen_containers();
        let mut app_data = gen_appdata(&containers);
        let logs = (1..=3).map(|i| format!("{i} {i}")).collect::<Vec<_>>();
        app_data.containers_start();
        app_data.update_log_by_id(logs, &ids[0]);

        app_data.log_start();

        let result = app_data.get_log_state();
        assert!(result.is_some());
        assert_eq!(result.as_ref().unwrap().selected(), Some(0));
        assert_eq!(result.unwrap().offset(), 0);

        let result = app_data.get_log_title();
        assert_eq!(result, " 1/3 - container_1 - image_1");
    }

    #[test]
    /// logs state end goes to the end of the logs list
    fn test_app_data_logs_end() {
        let (ids, containers) = gen_containers();
        let mut app_data = gen_appdata(&containers);
        let logs = (1..=3).map(|i| format!("{i} {i}")).collect::<Vec<_>>();
        app_data.containers_start();
        app_data.update_log_by_id(logs, &ids[0]);

        app_data.log_start();

        let result = app_data.get_log_state();
        assert!(result.is_some());
        assert_eq!(result.as_ref().unwrap().selected(), Some(0));
        assert_eq!(result.unwrap().offset(), 0);

        let result = app_data.get_log_title();
        assert_eq!(result, " 1/3 - container_1 - image_1");

        app_data.log_end();
        let result = app_data.get_log_state();
        assert!(result.is_some());
        assert_eq!(result.as_ref().unwrap().selected(), Some(2));
        assert_eq!(result.unwrap().offset(), 0);

        let result = app_data.get_log_title();
        assert_eq!(result, " 3/3 - container_1 - image_1");
    }

    #[test]
    /// logs state next works
    /// At end has no effect
    fn test_app_data_logs_next() {
        let (ids, containers) = gen_containers();
        let mut app_data = gen_appdata(&containers);
        let logs = (1..=3).map(|i| format!("{i} {i}")).collect::<Vec<_>>();
        app_data.containers_start();
        app_data.update_log_by_id(logs, &ids[0]);

        app_data.log_start();

        let result = app_data.get_log_state();
        assert!(result.is_some());
        assert_eq!(result.as_ref().unwrap().selected(), Some(0));
        assert_eq!(result.unwrap().offset(), 0);

        let result = app_data.get_log_title();
        assert_eq!(result, " 1/3 - container_1 - image_1");

        app_data.log_scroll(&ScrollDirection::Down);
        let result = app_data.get_log_state();
        assert!(result.is_some());
        assert_eq!(result.as_ref().unwrap().selected(), Some(1));
        assert_eq!(result.unwrap().offset(), 0);

        let result = app_data.get_log_title();
        assert_eq!(result, " 2/3 - container_1 - image_1");

        app_data.log_scroll(&ScrollDirection::Down);
        let result = app_data.get_log_state();
        assert!(result.is_some());
        assert_eq!(result.as_ref().unwrap().selected(), Some(2));
        assert_eq!(result.unwrap().offset(), 0);

        let result = app_data.get_log_title();
        assert_eq!(result, " 3/3 - container_1 - image_1");
        app_data.log_scroll(&ScrollDirection::Down);

        let result = app_data.get_log_state();
        assert!(result.is_some());
        assert_eq!(result.as_ref().unwrap().selected(), Some(2));
        assert_eq!(result.unwrap().offset(), 0);

        let result = app_data.get_log_title();
        assert_eq!(result, " 3/3 - container_1 - image_1");
    }

    #[test]
    /// logs state previous works
    /// previous at start has no effect
    fn test_app_data_logs_previous() {
        let (ids, containers) = gen_containers();
        let mut app_data = gen_appdata(&containers);
        let logs = (1..=3).map(|i| format!("{i} {i}")).collect::<Vec<_>>();
        app_data.containers_start();
        app_data.update_log_by_id(logs, &ids[0]);

        app_data.log_end();

        let result = app_data.get_log_state();
        assert!(result.is_some());
        assert_eq!(result.as_ref().unwrap().selected(), Some(2));
        assert_eq!(result.unwrap().offset(), 0);

        let result = app_data.get_log_title();
        assert_eq!(result, " 3/3 - container_1 - image_1");

        app_data.log_scroll(&ScrollDirection::Up);

        let result = app_data.get_log_state();
        assert!(result.is_some());
        assert_eq!(result.as_ref().unwrap().selected(), Some(1));
        assert_eq!(result.unwrap().offset(), 0);
        let result = app_data.get_log_title();
        assert_eq!(result, " 2/3 - container_1 - image_1");

        app_data.log_scroll(&ScrollDirection::Up);
        let result = app_data.get_log_state();
        assert!(result.is_some());
        assert_eq!(result.as_ref().unwrap().selected(), Some(0));
        assert_eq!(result.unwrap().offset(), 0);
        let result = app_data.get_log_title();
        assert_eq!(result, " 1/3 - container_1 - image_1");

        app_data.log_scroll(&ScrollDirection::Up);
        let result = app_data.get_log_state();
        assert!(result.is_some());
        assert_eq!(result.as_ref().unwrap().selected(), Some(0));
        assert_eq!(result.unwrap().offset(), 0);
        let result = app_data.get_log_title();
        assert_eq!(result, " 1/3 - container_1 - image_1");
    }

    // ********** //
    // Chart data //
    // ********** //

    #[test]
    /// Chart data returned correctly
    fn test_app_data_get_chart_data() {
        let (_ids, containers) = gen_containers();
        let mut app_data = gen_appdata(&containers);

        let result = app_data.get_chart_data();
        assert!(result.is_none());

        app_data.containers_start();

        let mut rx = NetworkBandwidth::new();
        rx.push(200);
        rx.push(100);
        rx.push(200);

        let mut tx = NetworkBandwidth::new();
        tx.push(300);
        tx.push(600);
        tx.push(900);

        if let Some(item) = app_data.get_container_by_id(&ContainerId::from("1")) {
            item.cpu_stats = VecDeque::from([CpuStats::new(1.2), CpuStats::new(1.2)]);
            item.mem_stats = VecDeque::from([ByteStats::new(1), ByteStats::new(2)]);
            item.rx = rx;
            item.tx = tx;
        }

        let result = app_data.get_chart_data();
        assert_eq!(
            result,
            Some(ChartsData {
                memory: ChartSeries {
                    dataset: vec![(0.0, 1.0), (1.0, 2.0)],
                    max: ByteStats::new(2),
                    current: ByteStats::new(2)
                },
                cpu: ChartSeries {
                    dataset: vec![(0.0, 1.2), (1.0, 1.2)],
                    max: CpuStats::new(1.2),
                    current: CpuStats::new(1.2)
                },
                rx: ChartSeries {
                    dataset: vec![(0.0, 0.0), (1.0, 100.0)],
                    max: BandwidthStat::new(100),
                    current: BandwidthStat::new(100)
                },
                tx: ChartSeries {
                    dataset: vec![(0.0, 300.0), (1.0, 300.0)],
                    max: BandwidthStat::new(300),
                    current: BandwidthStat::new(300)
                },
                state: State::Running(RunningState::Healthy)
            })
        );
    }

    // ************* //
    // Header Widths //
    // ************* //

    #[test]
    /// Header widths return correctly
    fn test_app_data_get_width() {
        let (_ids, containers) = gen_containers();
        let app_data = gen_appdata(&containers);

        let result = app_data.get_width();
        let expected = Columns {
            name: (Header::Name, 11),
            state: (Header::State, 9),
            status: (Header::Status, 9),
            cpu: (Header::Cpu, 6),
            mem: (Header::Memory, 7, 7),
            id: (Header::Id, 8),
            image: (Header::Image, 7),
            net_rx: (Header::Rx, 7),
            net_tx: (Header::Tx, 7),
        };
        assert_eq!(result, expected);
    }

    #[test]
    /// Header widths return correctly when some containers hidden
    fn test_app_data_get_width_filtered() {
        let (_ids, mut containers) = gen_containers();
        containers[0].name = ContainerName::from("some_longer_name_with_filter");
        let mut app_data = gen_appdata(&containers);

        let result = app_data.get_width();
        let expected = Columns {
            name: (Header::Name, 28),
            state: (Header::State, 9),
            status: (Header::Status, 9),
            cpu: (Header::Cpu, 6),
            mem: (Header::Memory, 7, 7),
            id: (Header::Id, 8),
            image: (Header::Image, 7),
            net_rx: (Header::Rx, 7),
            net_tx: (Header::Tx, 7),
        };

        assert_eq!(result, expected);
        app_data.filter_term_push('c');
        app_data.filter_containers();
        assert_eq!(result, expected);
    }

    // ***** //
    // Ports //
    // ***** //

    #[test]
    /// Returns selected containers ports ordered by private ip
    fn test_app_data_get_selected_ports() {
        let (_ids, containers) = gen_containers();
        let mut app_data = gen_appdata(&containers);

        app_data.containers.items[0].ports.push(ContainerPorts {
            ip: None,
            private: 10,
            public: Some(1),
        });
        app_data.containers.items[0].ports.push(ContainerPorts {
            ip: None,
            private: 11,
            public: Some(3),
        });
        app_data.containers.items[0].ports.push(ContainerPorts {
            ip: None,
            private: 4,
            public: Some(2),
        });

        // No containers selected
        let result = app_data.get_selected_ports();
        assert!(result.is_none());

        // Selected container & ports
        app_data.containers_start();
        let result = app_data.get_selected_ports();

        assert_eq!(
            result,
            Some((
                vec![
                    ContainerPorts {
                        ip: None,
                        private: 4,
                        public: Some(2)
                    },
                    ContainerPorts {
                        ip: None,
                        private: 10,
                        public: Some(1)
                    },
                    ContainerPorts {
                        ip: None,
                        private: 11,
                        public: Some(3)
                    },
                    ContainerPorts {
                        ip: None,
                        private: 8001,
                        public: None
                    }
                ],
                State::Running(RunningState::Healthy),
            ))
        );

        // Selected container & no ports
        app_data.containers_start();
        app_data.containers.items[0].ports = vec![];
        let result = app_data.get_selected_ports();

        assert_eq!(
            result,
            Some((vec![], State::Running(RunningState::Healthy)))
        );
    }

    // ************** //
    // Update mtehods //
    // ************** //

    #[test]
    /// Update stats functioning
    fn test_app_data_update_stats() {
        let (ids, containers) = gen_containers();

        let mut app_data = gen_appdata(&containers);

        let result = app_data.get_container_items();
        assert_eq!(result[0], containers[0]);

        app_data.update_stats_by_id(&ids[0], Some(10.0), Some(10), 10, 10, 10);

        let result = app_data.get_container_items();
        assert_ne!(result[0], containers[0]);
        assert_eq!(result[0].cpu_stats, VecDeque::from([CpuStats::new(10.0)]));
        assert_eq!(result[0].mem_stats, VecDeque::from([ByteStats::new(10)]));
        assert_eq!(result[0].mem_limit, ByteStats::new(10));

        let mut rx = NetworkBandwidth::new();
        rx.push(10);
        let mut tx = NetworkBandwidth::new();
        tx.push(10);
        assert_eq!(result[0].rx, rx);
        // VecDeque::from([ByteStats::new(10)]));
        assert_eq!(result[0].tx, tx);
        // VecDeque::from([ByteStats::new(10)]));
    }

    #[test]
    /// Update stats functioning
    fn test_app_data_update_containers() {
        let (_ids, containers) = gen_containers();
        let mut app_data = gen_appdata(&containers);
        let result_pre = app_data.get_container_items().to_owned();
        let input = vec![
            gen_container_summary(1, "paused"),
            gen_container_summary(2, "dead"),
        ];

        app_data.update_containers(input);
        let result_post = app_data.get_container_items().to_owned();
        assert_ne!(result_pre, result_post);
        assert_eq!(result_post[0].state, State::Paused);
        assert_eq!(result_post[1].state, State::Dead);
    }

    #[test]
    /// Update logs don't work if container is_oxker: true
    fn test_app_data_update_log_by_id_is_oxker() {
        let (ids, mut containers) = gen_containers();
        containers[0].is_oxker = true;
        let mut app_data = gen_appdata(&containers);
        let logs = (1..=3).map(|i| format!("{i} {i}")).collect::<Vec<_>>();

        app_data.update_log_by_id(logs, &ids[0]);
        app_data.log_start();

        let result = app_data.get_log_state();
        assert!(result.is_none());
    }

    // *************** //
    // Get logs method //
    // *************** //

    #[test]
    /// get_logs() returns vec of item, but the items are empty unless they are in the *visible" zone, based on height, index, and padding
    fn test_app_data_update_get_logs() {
        let (ids, containers) = gen_containers();

        let mut app_data = gen_appdata(&containers);

        app_data.containers_start();
        let logs = (0..=999).map(|i| format!("{i} {i}")).collect::<Vec<_>>();

        app_data.update_log_by_id(logs, &ids[0]);

        let result = app_data.get_logs(
            Size {
                width: 20,
                height: 10,
            },
            10,
        );
        for (index, item) in result.iter().enumerate() {
            if index < 979 {
                assert_eq!(item, &Text::from(""));
            } else {
                assert_eq!(item, &Text::from(format!("{index}")));
            }
        }

        let result = app_data.get_logs(
            Size {
                width: 20,
                height: 100,
            },
            20,
        );
        for (index, item) in result.iter().enumerate() {
            if index < 879 {
                assert_eq!(item, &Text::from(""));
            } else {
                assert_eq!(item, &Text::from(format!("{index}")));
            }
        }

        app_data.log_start();

        let result = app_data.get_logs(
            Size {
                width: 20,
                height: 10,
            },
            10,
        );
        for (index, item) in result.iter().enumerate() {
            if index > 20 {
                assert_eq!(item, &Text::from(""));
            } else {
                assert_eq!(item, &Text::from(format!("{index}")));
            }
        }

        for _ in 0..=500 {
            app_data.log_scroll(&ScrollDirection::Down);
        }
        let result = app_data.get_logs(
            Size {
                width: 20,
                height: 10,
            },
            10,
        );
        for (index, item) in result.iter().enumerate() {
            if (481..=521).contains(&index) {
                assert_eq!(item, &Text::from(format!("{index}")));
            } else {
                assert_eq!(item, &Text::from(""));
            }
        }
    }
}