cdx 0.1.23

Library and application for text file manipulation and command line data mining, a little like the gnu textutils
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
//! Handles conversion between named column sets and lists of column numbers
//! Also helps with selecting those columns from a line of text

use crate::matcher::MatchMaker;
use crate::prelude::*;
use crate::util::find_close;
use std::collections::HashSet;
use std::str;

/// What to do if there would be duplicate column names
#[derive(Debug, Copy, Clone, Default)]
pub enum DupColHandling {
    /// Fail if there are duplicate columns names
    #[default]
    Fail,
    /// Allow duplicate columns names, but write a message to stderr
    Allow,
    /// if "foo" is taken, try "foo1", then "foo2" until it's unique
    Numeric,
}

impl DupColHandling {
    /// new
    pub fn new(spec: &str) -> Result<Self> {
        if spec.eq_ignore_ascii_case("fail") {
            Ok(Self::Fail)
        } else if spec.eq_ignore_ascii_case("allow") {
            Ok(Self::Allow)
        } else if spec.eq_ignore_ascii_case("numeric") {
            Ok(Self::Numeric)
        } else {
            err!("Duplicate Column Mode must be one of : Fail, Allow, Numeric")
        }
    }
}

#[derive(Default, Clone, Debug)]
struct NameMap {
    from: String,
    to: String,
}
impl NameMap {
    fn new(spec: &str) -> Result<Self> {
        if let Some((a, b)) = spec.split_once('.') {
            Ok(Self { from: a.to_string(), to: b.to_string() })
        } else {
            err!("Format for rename is 'old.new' not '{spec}'")
        }
    }
}
impl fmt::Display for NameMap {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}.{}", self.from, self.to)
    }
}

/// build the CDX header for an output file
#[derive(Debug, Default, Clone)]
pub struct ColumnHeader {
    cols: Vec<String>,
    dups: DupColHandling,
    rename: Vec<NameMap>,
    sloppy: bool,
}

/// is 'name' a valid column name
#[must_use]
pub fn is_valid_column_name(name: &str) -> bool {
    get_col_name(name) == name.len()
}

fn make_valid_column_name(name: &str) -> String {
    if name.is_empty() {
        return "X_".to_string();
    }
    let mut out = String::new();
    let mut sp = name;
    let mut ch = sp.take_first();
    if ch.is_alphabetic() {
        out.push(ch);
    } else {
        out.push_str("X_");
    }
    while !sp.is_empty() {
        ch = sp.first();
        let nch = if ch.is_alphanumeric() { ch } else { '_' };
        out.push(nch);
        sp = sp.skip_first();
    }
    out
}

/// throw an error is name is not a valid column name
pub fn validate_column_name(name: &str) -> Result<()> {
    if is_valid_column_name(name) { Ok(()) } else { err!("Invalid column name {}", name) }
}

/// extract column from line
#[must_use]
pub fn get_col(data: &[u8], col: usize, delim: u8) -> &[u8] {
    for (n, s) in data.split(|ch| *ch == delim).enumerate() {
        if n == col {
            return if !s.is_empty() && s.last().unwrap() == &b'\n' {
                &s[0..s.len() - 1]
            } else {
                s
            };
        }
    }
    &data[0..0]
}

impl ColumnHeader {
    /// new
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }
    /// set the `DupColHandling` mode
    pub const fn set_handling(&mut self, dups: DupColHandling) {
        self.dups = dups;
    }
    /// clear
    pub fn clear(&mut self) {
        self.cols.clear();
    }
    /// set some renames
    pub fn rename(&mut self, spec: &str) -> Result<()> {
        if !spec.is_empty() {
            for x in spec.split(',') {
                self.rename.push(NameMap::new(x)?);
            }
        }
        Ok(())
    }
    /// set sloppy
    pub const fn rename_sloppy(&mut self) {
        self.sloppy = true;
    }
    /// get field names suitable for `lookup()`
    #[must_use]
    pub fn field_names(&self) -> Vec<&str> {
        let mut v: Vec<&str> = Vec::with_capacity(self.cols.len());
        for x in &self.cols {
            v.push(x);
        }
        v
    }
    /// add all of the columns from 'cols'
    pub fn push_all(&mut self, cols: &StringLine) -> Result<()> {
        for x in cols {
            self.push(x)?;
        }
        Ok(())
    }
    /// add all of the columns from 'cols', unchecked
    pub fn push_all_unchecked(&mut self, cols: &StringLine) {
        for x in cols {
            self.push_unchecked(x);
        }
    }

    /// do we already have this column name
    #[must_use]
    pub fn contains(&self, name: &str) -> bool {
        for x in &self.cols {
            if x == name {
                return true;
            }
        }
        false
    }

    /// add new column name, no checking
    pub fn push_unchecked(&mut self, name: &str) {
        self.cols.push(name.to_string());
    }
    /// return err if unused renames
    pub fn check_rename(&self) -> Result<()> {
        if !self.sloppy & !self.rename.is_empty() {
            let mut s = self.rename[0].to_string();
            for x in self.rename.iter().skip(1) {
                s.push(',');
                s.push_str(&x.to_string());
            }
            err!("Unused rename : '{}'", s)
        } else {
            Ok(())
        }
    }
    fn valid_column_name(name: &str) -> String {
        if is_valid_column_name(name) { name.to_string() } else { make_valid_column_name(name) }
    }

    /// add new column name
    pub fn push(&mut self, name: &str) -> Result<()> {
        let name = Self::valid_column_name(name);
        if self.contains(&name) {
            let mut key: Option<usize> = None;
            for (i, x) in self.rename.iter().enumerate() {
                if x.from == name {
                    key = Some(i);
                    break;
                }
            }
            if let Some(k) = key {
                if self.contains(&self.rename[k].to) {
                    return err!(
                        "Applied rename of {} to {}, but {} was already used",
                        self.rename[k].from,
                        self.rename[k].to,
                        self.rename[k].to
                    );
                }
                self.cols.push(self.rename[k].to.clone());
                self.rename.remove(k);
                return Ok(());
            }
            match self.dups {
                DupColHandling::Fail => return err!("Duplicate column name {}", name),
                DupColHandling::Allow => {
                    eprintln!("Warning : creating duplicate column name {name}");
                    self.cols.push(name);
                }
                DupColHandling::Numeric => {
                    for x in 1..10000 {
                        let new_name = format!("{name}{x}");
                        if !self.contains(&new_name) {
                            self.cols.push(new_name);
                            break;
                        }
                    }
                }
            }
        } else {
            self.cols.push(name);
        }
        Ok(())
    }

    /// get new string, which is the full CDX header, including newline
    #[must_use]
    pub fn get_head(&self, text: &TextFileMode) -> String {
        let mut res = String::with_capacity(self.get_size() + 6);
        if text.head_mode.has_cdx() {
            res.push_str(" CDX");
            res.push(text.delim as char);
        }
        self.add_head(&mut res, text);
        res.push('\n');
        res
    }

    /// get new string, which is the column names joined
    #[must_use]
    pub fn get_head_short(&self, text: &TextFileMode) -> String {
        let mut res = String::with_capacity(self.get_size());
        self.add_head(&mut res, text);
        res
    }

    fn get_size(&self) -> usize {
        self.cols.iter().map(String::len).sum::<usize>() + self.cols.len() - 1
    }
    /// append column names, joined
    #[allow(clippy::trivially_copy_pass_by_ref)]
    fn add_head(&self, res: &mut String, text: &TextFileMode) {
        if self.cols.is_empty() {
            return;
        }
        res.push_str(&self.cols[0]);
        for x in self.cols.iter().skip(1) {
            res.push(text.delim as char);
            res.push_str(x);
        }
    }
}

/// A column set is a collection of column specifications, which when interpreted
/// in the context of a set of named columns, produces a list of column numbers
///
/// It contains a bunch of "yes" specs and "no" specs.
/// If there are no "yes" specs, all columns are marked "yes"
/// The resulting list of column numbers is all of the "yes" columns in order,
/// minus any "no" columns. Thus if a column appears in both, it will be excluded.
/// # Examples
///
/// ```
///    use cdx::column::ColumnSet;
///    cdx::util::init();
///    let header: [&str; 5] = ["zero", "one", "two", "three", "four"];
///
///    let mut s = ColumnSet::new();
///    s.lookup(&header);
///    assert_eq!(s.get_cols_num(), &[0,1,2,3,4]);
///
///    let mut s = ColumnSet::new();
///    s.add_yes("-");
///    s.lookup(&header);
///    assert_eq!(s.get_cols_num(), &[0,1,2,3,4]);
///
///    let mut s = ColumnSet::new();
///    s.add_yes("one-three");
///    s.lookup(&header);
///    assert_eq!(s.get_cols_num(), &[1,2,3]);
///
///    let mut s = ColumnSet::new();
///    s.add_no("three,one");
///    s.lookup(&header);
///    assert_eq!(s.get_cols_num(), &[0,2,4]);
///
///    let mut s = ColumnSet::new();
///    s.add_no("+4-+2");
///    s.lookup(&header);
///    assert_eq!(s.get_cols_num(), &[0,4]);
///
///    let mut s = ColumnSet::new();
///    s.add_yes("(range,>s<=two)");
///    s.lookup(&header);
///    assert_eq!(s.get_cols_num(), &[2,3]);
/// ```
#[derive(Debug, Default, Clone)]
pub struct ColumnSet {
    /// specs for columns to include, e.g. "1-3", "one-three", "(range,>s<=two)"
    pub pos: Vec<String>,
    /// specs for columns to exclude, e.g. "1-3", "one-three", "(range,>s<=two)"
    pub neg: Vec<String>,
    /// the resulting list of column numbers, in order, after lookup
    pub columns: Vec<OutCol>,
    /// have we done the lookup yet?
    pub did_lookup: bool,
    /// any transformations to apply to the column values
    pub trans: TransList,
    /// any aggregations to apply to the column values
    pub agg: AggList,
}

/// named output columns
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct OutCol {
    /// column number
    pub num: usize,
    /// column name, might be empty if no name available
    pub name: String,
    /// which `TransList` to use
    pub oc_num_trans: Option<usize>,
    /// which `AggList` to use
    pub oc_num_agg: Option<usize>,
}

impl OutCol {
    /// new
    #[must_use]
    pub fn new(num: usize, name: &str) -> Self {
        Self { num, name: name.to_string(), oc_num_trans: None, oc_num_agg: None }
    }
    // new with name and trans
    // #[must_use]
    // pub fn new_trans(num: usize, name: &str, trans: usize) -> Self {
    //     Self { num, name: name.to_string(), oc_num_trans: Some(trans) }
    // }
    /// new with empty name
    #[must_use]
    pub const fn from_num(num: usize) -> Self {
        Self { num, name: String::new(), oc_num_trans: None, oc_num_agg: None }
    }
    // new with empty name but a trans
    // #[must_use]
    // pub const fn from_num_trans(num: usize, trans: usize) -> Self {
    //     Self { num, name: String::new(), oc_num_trans: Some(trans) }
    // }
}

/// A `ColumnSet` with associated string
#[derive(Debug, Default, Clone)]
pub struct ScopedValue {
    cols: ColumnSet,
    value: String,
}

impl ScopedValue {
    /// one string
    pub fn new(spec: &str, del: char) -> Result<Self> {
        let mut s = Self::default();
        if spec.is_empty() {
            return Ok(s);
        }
        let mut spec = spec;
        let ch = spec.first();
        if ch == del {
            spec.skip_first();
            if spec.is_empty() {
                s.value.push(del);
                return Ok(s);
            }
            let ch = spec.first();
            if ch == del {
                s.value.push(del);
            }
        }
        while !spec.is_empty() {
            let ch = spec.take_first();
            if ch == del {
                s.cols.add_yes(spec)?;
                return Ok(s);
            }
            s.value.push(ch);
        }
        Ok(s)
    }
    /// two strings
    pub fn new2(value: &str, cols: &str) -> Result<Self> {
        let mut s = Self::default();
        s.cols.add_yes(cols)?;
        s.value = value.to_string();
        Ok(s)
    }
    /// resolve named columns
    pub fn lookup(&mut self, field_names: &[&str]) -> Result<()> {
        self.cols.lookup(field_names)
    }
}

/// A per-column value
#[derive(Debug, Default, Clone)]
pub struct ScopedValues {
    default: String,
    data: Vec<ScopedValue>,

    has_value: Vec<bool>,
    strings: Vec<String>,
    ints: Vec<isize>,
    floats: Vec<f64>,
}

impl ScopedValues {
    /// new
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }
    /// value for column not otherwise assigned a value
    pub fn set_default(&mut self, d: &str) {
        self.default = d.to_string();
    }
    /// resolve named columns
    pub fn lookup(&mut self, field_names: &[&str]) -> Result<()> {
        self.has_value.clear();
        self.has_value.resize(field_names.len(), false);
        self.strings.clear();
        self.strings.resize(field_names.len(), self.default.clone());
        for x in &mut self.data {
            x.lookup(field_names)?;
            for i in 0..x.cols.columns.len() {
                let j = x.cols.columns[i].num;
                self.strings[j].clone_from(&x.value);
                self.has_value[j] = true;
            }
        }
        Ok(())
    }
    /// do the work so that `get_int()` will work properly
    pub fn make_ints(&mut self) -> Result<()> {
        self.ints.clear();
        for i in 0..self.strings.len() {
            self.ints[i] = self.get(i).to_isize_whole(self.get(i).as_bytes(), "number")?;
        }
        Ok(())
    }
    /// do the work so that `get_int()` will work properly
    pub fn make_floats(&mut self) -> Result<()> {
        self.floats.clear();
        for i in 0..self.strings.len() {
            self.floats[i] = self.get(i).to_f64_whole(self.get(i).as_bytes(), "float")?;
        }
        Ok(())
    }

    /// add one `ScopedValue`
    pub fn add(&mut self, spec: &str, del: char) -> Result<()> {
        self.data.push(ScopedValue::new(spec, del)?);
        Ok(())
    }
    /// add one `ScopedValue`
    pub fn add2(&mut self, value: &str, cols: &str) -> Result<()> {
        self.data.push(ScopedValue::new2(value, cols)?);
        Ok(())
    }
    /// get appropriate value for the column
    #[must_use]
    pub fn get(&self, col: usize) -> &str {
        if col < self.strings.len() { &self.strings[col] } else { self.strings.last().unwrap() }
    }
    /// get appropriate int value for the column
    #[must_use]
    pub fn get_int(&self, col: usize) -> isize {
        if col < self.ints.len() { self.ints[col] } else { *self.ints.last().unwrap() }
    }
    /// get appropriate int value for the column
    #[must_use]
    pub fn get_float(&self, col: usize) -> f64 {
        if col < self.floats.len() { self.floats[col] } else { *self.floats.last().unwrap() }
    }
    /// has this column been assigned a value?
    #[must_use]
    pub fn has_value(&self, col: usize) -> bool {
        if col < self.has_value.len() { self.has_value[col] } else { false }
    }
    /// Have any column been assigned values?
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.data.is_empty()
    }
}

/// Write some output
pub trait ColumnFun {
    /// write the column names (called once)
    fn add_names(&self, w: &mut ColumnHeader, head: &StringLine) -> Result<()>;
    /// write the column values (called many times)
    fn write(&mut self, w: &mut dyn Write, line: &TextLine, text: &TextFileMode) -> Result<()>;
    /// resolve any named columns
    fn lookup(&mut self, field_names: &[&str]) -> Result<()>;
}

/// write a single column
#[derive(Debug, Default)]
pub struct ColumnExpr {
    name: String,
    expr: Expr,
}

impl ColumnExpr {
    /// new from Expr or Name:Expr
    pub fn new(spec: &str) -> Result<Self> {
        if let Some((a, b)) = spec.split_once(':') {
            Ok(Self { name: a.to_string(), expr: Expr::new(b)? })
        } else {
            Ok(Self { name: String::new(), expr: Expr::new(spec)? })
        }
    }
}

impl ColumnFun for ColumnExpr {
    fn add_names(&self, w: &mut ColumnHeader, _head: &StringLine) -> Result<()> {
        w.push(&self.name)
    }
    /// write the column values (called many times)
    fn write(&mut self, w: &mut dyn Write, line: &TextLine, _text: &TextFileMode) -> Result<()> {
        write!(w, "{}", self.expr.eval(line))?;
        Ok(())
    }
    /// resolve any named columns
    fn lookup(&mut self, field_names: &[&str]) -> Result<()> {
        self.expr.lookup(field_names)
    }
}

/// write a single column
#[derive(Debug, Default)]
pub struct ColumnSingle {
    col: NamedCol,
    new_name: String,
}

impl ColumnSingle {
    /// new from `NamedCol`
    #[must_use]
    pub fn with_named_col(col: &NamedCol) -> Self {
        Self { col: col.clone(), new_name: String::new() }
    }
    /// new from name
    pub fn with_name(col: &str) -> Result<Self> {
        Ok(Self { col: NamedCol::new_from(col)?, new_name: String::new() })
    }
}

impl ColumnFun for ColumnSingle {
    fn add_names(&self, w: &mut ColumnHeader, head: &StringLine) -> Result<()> {
        if self.new_name.is_empty() { w.push(&head[self.col.num]) } else { w.push(&self.new_name) }
    }
    /// write the column values (called many times)
    fn write(&mut self, w: &mut dyn Write, line: &TextLine, text: &TextFileMode) -> Result<()> {
        text.write(w, &line[self.col.num])?;
        //        w.write_all(&line[self.col.num])?;
        Ok(())
    }
    /// resolve any named columns
    fn lookup(&mut self, field_names: &[&str]) -> Result<()> {
        self.col.lookup(field_names)
    }
}

/// write the whole line
#[derive(Debug, Default, Copy, Clone)]
pub struct ColumnWhole;

impl ColumnFun for ColumnWhole {
    /// write the column names (called once)
    fn add_names(&self, w: &mut ColumnHeader, head: &StringLine) -> Result<()> {
        w.push_all(head)
    }
    /// write the column values (called many times)
    fn write(&mut self, w: &mut dyn Write, line: &TextLine, _text: &TextFileMode) -> Result<()> {
        w.write_all(&line.line()[0..line.line().len() - 1])?;
        Ok(())
    }
    /// resolve any named columns
    fn lookup(&mut self, _field_names: &[&str]) -> Result<()> {
        Ok(())
    }
}

/// write an increasing count, e.g. cat -n
#[derive(Debug, Default, Clone)]
pub struct ColumnCount {
    num: isize,
    name: String,
}

impl ColumnCount {
    /// new
    #[must_use]
    pub fn new(num: isize, name: &str) -> Self {
        Self { num, name: name.to_string() }
    }
}

impl ColumnFun for ColumnCount {
    /// write the column names (called once)
    fn add_names(&self, w: &mut ColumnHeader, _head: &StringLine) -> Result<()> {
        w.push(&self.name)
    }
    /// write the column values (called many times)
    fn write(&mut self, w: &mut dyn Write, _line: &TextLine, _text: &TextFileMode) -> Result<()> {
        w.write_all(self.num.to_string().as_bytes())?;
        self.num += 1;
        Ok(())
    }
    /// resolve any named columns
    fn lookup(&mut self, _field_names: &[&str]) -> Result<()> {
        Ok(())
    }
}

/// write a fixed value
#[derive(Debug, Default, Clone)]
pub struct ColumnLiteral {
    value: Vec<u8>,
    name: String,
}

impl ColumnLiteral {
    /// new
    #[must_use]
    pub fn new(value: &[u8], name: &str) -> Self {
        Self { value: value.to_vec(), name: name.to_string() }
    }
}

impl ColumnFun for ColumnLiteral {
    /// write the column names (called once)
    fn add_names(&self, w: &mut ColumnHeader, _head: &StringLine) -> Result<()> {
        w.push(&self.name)
    }
    /// write the column values (called many times)
    fn write(&mut self, w: &mut dyn Write, _line: &TextLine, text: &TextFileMode) -> Result<()> {
        text.write(w, &self.value)?;
        Ok(())
    }
    /// resolve any named columns
    fn lookup(&mut self, _field_names: &[&str]) -> Result<()> {
        Ok(())
    }
}

impl fmt::Debug for dyn ColumnFun {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "ColumnFun")
    }
}

impl ColumnSet {
    /// Create an empty column set, which selects all columns.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }
    /// is empty?
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.pos.is_empty() && self.neg.is_empty()
    }

    /// Create an column set from a spec, e.g. "1-3"
    pub fn from_spec(spec: &str) -> Result<Self> {
        let mut s = Self::default();
        s.add_yes(spec)?;
        Ok(s)
    }

    /// Add some columns to be selected
    pub fn add_yes(&mut self, spec: &str) -> Result<()> {
        self.add(spec, false)
    }

    /// Add some columns to be rejected.
    pub fn add_no(&mut self, spec: &str) -> Result<()> {
        self.add(spec, true)
    }

    /// Add a single range, "yes" or "no" based on a flag.
    pub fn add_one(&mut self, s: &str, negate: bool) {
        if let Some(stripped) = s.strip_prefix('~') {
            let st = stripped.to_string();
            if negate {
                self.pos.push(st);
            } else {
                self.neg.push(st);
            }
        } else {
            let st = s.to_string();
            if negate {
                self.neg.push(st);
            } else {
                self.pos.push(st);
            }
        }
    }

    fn find_trans(spec: &str) -> Option<(&str, &str)> {
        let mut last_was_plus = false;
        for (i, x) in spec.char_indices() {
            if last_was_plus {
                if x.is_alphabetic() {
                    return Some((&spec[0..i - 1], &spec[i..]));
                }
                last_was_plus = false;
            } else if x == '+' {
                last_was_plus = true;
            }
        }
        None
    }
    /// Add a list or ranges, "yes" or "no" based on a flag.
    pub fn add(&mut self, in_spec: &str, negate: bool) -> Result<()> {
        let mut spc = in_spec;
        if let Some((a, b)) = spc.split_once("::") {
            spc = a;
            for a in b.split('+') {
                self.agg.push(a)?;
            }
        }
        if let Some((a, b)) = Self::find_trans(spc) {
            spc = a;
            self.trans = TransList::new(b)?;
        }
        loop {
            if spc.first() == '(' {
                let pos = find_close(spc)?;
                self.add_one(&spc[..pos], negate);
                spc = &spc[pos..];
                if spc.is_empty() {
                    break;
                }
            } else if let Some((a, b)) = spc.split_once(',') {
                self.add_one(a, negate);
                spc = b;
            } else {
                self.add_one(spc, negate);
                break;
            }
        }
        Ok(())
    }

    /// Turn column name into column number
    /// To also handle numbers and ranges, use `lookup1`
    /// # Examples
    ///
    /// ```
    ///    use cdx::column::ColumnSet;
    ///    assert_eq!(ColumnSet::lookup_col(&["zero", "one", "two"], "one").unwrap(), 1);
    /// ```
    pub fn lookup_col(field_names: &[&str], colname: &str) -> Result<usize> {
        for f in field_names.iter().enumerate() {
            if f.1 == &colname {
                return Ok(f.0);
            }
        }
        err!("{} not found", colname)
    }
    /*
        /// turn a u8 column name into a column number
        pub fn lookup_col2(field_names: &[&str], colname: &[u8]) -> Result<usize> {
        let name = str::from_utf8_lossy(colname);
            for f in field_names.iter().enumerate() {
                if *f.1 == name {
                    return Ok(f.0);
                }
            }
            err!("{:?} not found", &colname)
        }
    */
    /// resolve a single name or number into a column number
    /// # Examples
    ///
    /// ```
    ///    use cdx::column::ColumnSet;
    ///    assert_eq!(ColumnSet::single(&["zero", "one", "two"], "+1").unwrap(), 2);
    /// ```
    pub fn single(field_names: &[&str], colname: &str) -> Result<usize> {
        if let Some(stripped) = colname.strip_prefix('+') {
            let n = stripped.to_usize_whole(colname.as_bytes(), "column")?;
            let len = field_names.len();
            if n > len { err!("Column {} out of bounds", colname) } else { Ok(len - n) }
        } else {
            let ch = colname.first();
            if ch.is_ascii_digit() && ch != '0' {
                let n = colname.to_usize_whole(colname.as_bytes(), "column")?;
                if n < 1 { err!("Column {} out of bounds", colname) } else { Ok(n - 1) }
            } else {
                Self::lookup_col(field_names, colname)
            }
        }
    }

    /// Return all the fields that match the Matcher
    fn match_range(field_names: &[&str], rng: &str) -> Result<Vec<usize>> {
        let mut ret = Vec::new();
        let c = MatchMaker::make(rng)?;
        for f in field_names.iter().enumerate() {
            if c.smatch(f.1) {
                // allow case insensitive?
                ret.push(f.0);
            }
        }
        Ok(ret)
    }
    fn to_outcols(data: &[usize], name: &str) -> Vec<OutCol> {
        let mut ret = Vec::with_capacity(data.len());
        for x in data {
            ret.push(OutCol::new(*x, name));
        }
        ret
    }

    /// turn comma delimited list of ranges into list of possibly named column numbers
    pub fn ranges(field_names: &[&str], rng: &str) -> Result<Vec<OutCol>> {
        let mut c = Self::new();
        c.add_yes(rng)?;
        c.lookup(field_names)?;
        Ok(c.get_cols_full())
    }
    /// turn range into list of column numbers
    fn range(field_names: &[&str], rng: &str) -> Result<Vec<OutCol>> {
        if rng.is_empty() {
            return err!("Empty Range {}", rng);
        }
        let (name, range) = match rng.split_once(':') {
            None => ("", rng),
            Some(x) => x,
        };

        let ch = range.first();
        if ch == '(' {
            return Ok(Self::to_outcols(
                &Self::match_range(field_names, &range[1..range.len() - 1])?,
                name,
            ));
        }
        let mut parts: Vec<&str> = range.split('-').collect();
        if parts.len() > 2 {
            return err!("Malformed Range {}", rng);
        }
        if parts[0].is_empty() {
            parts[0] = "1";
        }

        let start: usize;
        let end = if parts.len() == 1 {
            start = Self::single(field_names, parts[0])?;
            start
        } else {
            if parts[1].is_empty() {
                parts[1] = "+1";
            }
            start = Self::single(field_names, parts[0])?;
            Self::single(field_names, parts[1])?
        };

        if start > end {
            // throw new CdxException("start > end, i.e. {" + parts.get(0) + " > " + parts.get(1));
            return err!("Start greater than end : {}", rng);
        }
        let mut res = Vec::new();
        for i in start..=end {
            res.push(OutCol::new(i, name));
        }
        Ok(res)
    }

    /// resolve `ColumnSet` in context of the column names from an input file
    /// # Examples
    ///
    /// ```
    ///    use cdx::column::ColumnSet;
    ///    let header: [&str; 5] = ["zero", "one", "two", "three", "four"];
    ///    let mut s = ColumnSet::new();
    ///    s.add_no("two");
    ///    s.lookup(&header);
    ///    assert_eq!(s.get_cols_num(), &[0,1,3,4]);
    /// ```
    pub fn lookup(&mut self, field_names: &[&str]) -> Result<()> {
        self.trans.lookup(field_names)?;
        // self.agg.lookup(field_names)?;
        self.did_lookup = true;
        self.columns = Vec::new();
        let mut no_cols: HashSet<usize> = HashSet::new();

        for s in &self.neg {
            for x in Self::range(field_names, s)? {
                no_cols.insert(x.num);
            }
        }

        if self.pos.is_empty() {
            for x in 0..field_names.len() {
                if !no_cols.contains(&x) {
                    self.columns.push(OutCol::from_num(x));
                }
            }
        } else {
            for s in &self.pos {
                for x in Self::range(field_names, s)? {
                    if !no_cols.contains(&x.num) {
                        self.columns.push(x);
                    }
                }
            }
        }
        Ok(())
    }

    /// Select columns from input line based on `ColumnSet`. Fail if input is too short. """
    /// # Examples
    ///
    /// ```
    ///    use cdx::column::ColumnSet;
    ///    let header: [&str; 5] = ["zero", "one", "two", "three", "four"];
    ///    let mut s = ColumnSet::new();
    ///    s.add_no("two");
    ///    s.lookup(&header);
    ///    let v = ["Zeroth", "First", "Second", "Third", "Fourth", "Fifth"];
    ///    let mut res = Vec::new();
    ///    s.select(&v, &mut res);
    ///    assert_eq!(res, vec!["Zeroth", "First", "Third", "Fourth"]);
    /// ```
    pub fn select<T: AsRef<str> + Clone>(&self, cols: &[T], result: &mut Vec<T>) -> Result<()> {
        if !self.did_lookup {
            return cdx_err(CdxError::NeedLookup);
        }
        result.clear();
        for x in &self.columns {
            if x.num < cols.len() {
                result.push(cols[x.num].clone());
            } else {
                return err!(
                    "Line has only {} columns, but column {} was requested.",
                    cols.len(),
                    x.num + 1
                );
            }
        }
        Ok(())
    }

    /// write the appropriate selection from the given columns
    /// trying to write a non-existent column is an error
    pub fn write(&self, w: &mut dyn Write, cols: &[&str], delim: &str) -> Result<()> {
        if !self.did_lookup {
            return cdx_err(CdxError::NeedLookup);
        }
        let mut iter = self.columns.iter();
        match iter.next() {
            None => {}
            Some(first) => {
                w.write_all(cols[first.num].as_bytes())?;

                for x in iter {
                    w.write_all(delim.as_bytes())?;
                    if x.num < cols.len() {
                        w.write_all(cols[x.num].as_bytes())?;
                    } else {
                        return err!(
                            "Line has only {} columns, but column {} was requested.",
                            cols.len(),
                            x.num + 1
                        );
                    }
                }
            }
        }
        w.write_all(b"\n")?;
        Ok(())
    }

    /// write the appropriate selection from the given columns
    pub fn write2(&self, w: &mut dyn Write, cols: &TextLine, delim: u8) -> Result<()> {
        if !self.did_lookup {
            return cdx_err(CdxError::NeedLookup);
        }
        let mut iter = self.columns.iter();
        match iter.next() {
            None => {}
            Some(first) => {
                w.write_all(&cols[first.num])?;
                for x in iter {
                    w.write_all(&[delim])?;
                    w.write_all(cols.get(x.num))?;
                }
            }
        }
        w.write_all(b"\n")?;
        Ok(())
    }

    fn fetch<'a>(
        col: &'a OutCol,
        mut_trans: &'a mut TransList,
        cols: &'a TextLine,
    ) -> Result<&'a [u8]> {
        mut_trans.trans(cols.get(col.num), cols)
    }

    /// write the appropriate selection from the given columns, but no trailing newline
    pub fn write3(
        &mut self,
        w: &mut dyn Write,
        cols: &TextLine,
        text: &TextFileMode,
    ) -> Result<()> {
        if !self.did_lookup {
            return cdx_err(CdxError::NeedLookup);
        }
        if self.columns.is_empty() {
            return Ok(());
        }
        if self.agg.is_empty() {
            text.write(w, Self::fetch(&self.columns[0], &mut self.trans, cols)?)?;
            for i in 1..self.columns.len() {
                w.write_all(&[text.delim])?;
                text.write(w, Self::fetch(&self.columns[i], &mut self.trans, cols)?)?;
            }
        } else {
            let mut is_first = true;
            for agg in &mut self.agg.v {
                agg.reset();
                for i in 0..self.columns.len() {
                    let val = Self::fetch(&self.columns[i], &mut self.trans, cols)?;
                    agg.add(val);
                }
                if is_first {
                    is_first = false;
                } else {
                    w.write_all(&[text.delim])?;
                }
                agg.write(w, cols, text)?;
            }
        }
        Ok(())
    }

    /// write the appropriate selection from the given columns, but no trailing newline
    pub fn write3s(&self, w: &mut dyn Write, cols: &StringLine, delim: u8) -> Result<()> {
        if !self.did_lookup {
            return cdx_err(CdxError::NeedLookup);
        }
        let mut iter = self.columns.iter();
        match iter.next() {
            None => {}
            Some(first) => {
                w.write_all(cols.get(first.num).as_bytes())?;
                for x in iter {
                    w.write_all(&[delim])?;
                    w.write_all(cols.get(x.num).as_bytes())?;
                }
            }
        }
        Ok(())
    }

    /// write the appropriate selection from the given columns, but no trailing newline
    /// trying to write a non-existent column writes the provided default value
    pub fn write_sloppy(&self, cols: &[&str], rest: &str, w: &mut dyn Write) -> Result<()> {
        if !self.did_lookup {
            return cdx_err(CdxError::NeedLookup);
        }
        for x in &self.columns {
            if x.num < cols.len() {
                w.write_all(cols[x.num].as_bytes())?;
            } else {
                w.write_all(rest.as_bytes())?;
            }
        }
        Ok(())
    }

    /// Select columns from input line based on `ColumnSet`, fill in default if line is too short """
    /// # Examples
    ///
    /// ```
    ///    use cdx::column::ColumnSet;
    ///    let header: [&str; 5] = ["zero", "one", "two", "three", "four"];
    ///    let mut s = ColumnSet::new();
    ///    s.add_no("two");
    ///    s.lookup(&header);
    ///    let v = ["Zeroth", "First", "Second", "Third"];
    ///    let mut res = Vec::new();
    ///    s.select_sloppy(&v, &"extra", &mut res);
    ///    assert_eq!(res, vec!["Zeroth", "First", "Third", "extra"]);
    /// ```
    pub fn select_sloppy<T: AsRef<str> + Clone>(
        &self,
        cols: &[T],
        restval: &T,
        result: &mut Vec<T>,
    ) -> Result<()> {
        if !self.did_lookup {
            return cdx_err(CdxError::NeedLookup);
        }
        result.clear();
        for x in &self.columns {
            if x.num < cols.len() {
                result.push(cols[x.num].clone());
            } else {
                result.push(restval.clone());
            }
        }
        Ok(())
    }

    /// return owned columns by const reference
    #[must_use]
    pub const fn get_cols(&self) -> &Vec<OutCol> {
        &self.columns
    }

    /// steal owned columns by value
    #[allow(clippy::missing_const_for_fn)] // clippy bug
    #[must_use]
    pub fn get_cols_full(self) -> Vec<OutCol> {
        self.columns
    }

    /// get owned column numbers
    #[must_use]
    pub fn get_cols_num(&self) -> Vec<usize> {
        let mut v = Vec::with_capacity(self.columns.len());
        for x in &self.columns {
            v.push(x.num);
        }
        v
    }

    /// Shorthand to look up some columns
    /// # Examples
    ///
    /// ```
    ///    use cdx::column::ColumnSet;
    ///    let header: [&str; 5] = ["zero", "one", "two", "three", "four"];
    ///    assert_eq!(ColumnSet::lookup_cols("~2-3", &header).unwrap(), &[0,3,4]);
    /// ```
    pub fn lookup_cols(spec: &str, names: &[&str]) -> Result<Vec<usize>> {
        let mut s = Self::new();
        s.add_yes(spec)?;
        s.lookup(names)?;
        Ok(s.get_cols_num())
    }

    /// Shorthand to look up some columns, with names
    pub fn lookup_cols_full(spec: &str, names: &[&str]) -> Result<Vec<OutCol>> {
        let mut s = Self::new();
        s.add_yes(spec)?;
        s.lookup(names)?;
        Ok(s.get_cols_full())
    }

    /// Shorthand to look up a single column
    /// To look up a single named column, `lookup_col` is also available
    /// # Examples
    ///
    /// ```
    ///    use cdx::column::ColumnSet;
    ///    let header: [&str; 5] = ["zero", "one", "two", "three", "four"];
    ///    assert_eq!(ColumnSet::lookup1("three", &header).unwrap(), 3);
    /// ```
    pub fn lookup1(spec: &str, names: &[&str]) -> Result<usize> {
        let mut s = Self::new();
        s.add_yes(spec)?;
        s.lookup(names)?;
        if s.get_cols().len() != 1 {
            return err!(
                "Spec {} resolves to {} columns, rather than a single column",
                spec,
                s.get_cols().len()
            );
        }
        Ok(s.get_cols_num()[0])
    }
}

/// Write the columns with a custom delimiter
pub struct ColumnClump {
    cols: Box<dyn ColumnFun>,
    name: String,
    text: TextFileMode,
}
impl fmt::Debug for ColumnClump {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "ColumnClump")
    }
}

impl ColumnClump {
    /// new `ColumnClump` from parts
    #[must_use]
    pub fn new(cols: Box<dyn ColumnFun>, name: &str, delim: u8) -> Self {
        let text = TextFileMode { delim, ..Default::default() };
        Self { cols, name: name.to_string(), text }
    }
    /// new `ColumnClump` from spec : DelimOutcol:Columns
    /// e.g. ,group:1-3
    pub fn from_spec(orig_spec: &str) -> Result<Self> {
        let mut spec = orig_spec;
        if spec.is_empty() {
            return err!("Can't construct a group from an empty string");
        }
        let delim = spec.take_first();
        if delim.len_utf8() != 1 {
            return err!("Delimiter must be a plain ascii character : {}", orig_spec);
        }
        let parts = spec.split_once(':');
        if parts.is_none() {
            return err!("No colon found. Group format is DelimOutname:Columns : {}", orig_spec);
        }
        let parts = parts.unwrap();
        let mut g = ColumnSet::new();
        g.add_yes(parts.1)?;
        let cols = Box::new(ReaderColumns::new(g));
        let text = TextFileMode { delim: delim as u8, ..Default::default() };
        Ok(Self { cols, name: parts.0.to_string(), text })
    }
}

impl ColumnFun for ColumnClump {
    fn write(&mut self, w: &mut dyn Write, line: &TextLine, _text: &TextFileMode) -> Result<()> {
        self.cols.write(w, line, &self.text)?;
        Ok(())
    }

    fn add_names(&self, w: &mut ColumnHeader, _head: &StringLine) -> Result<()> {
        w.push(&self.name)
    }
    fn lookup(&mut self, field_names: &[&str]) -> Result<()> {
        self.cols.lookup(field_names)
    }
}

/// Selection of columns from a Reader
#[derive(Debug)]
pub struct ReaderColumns {
    columns: ColumnSet,
}

impl ReaderColumns {
    /// new `ReaderColumns`
    #[must_use]
    pub const fn new(columns: ColumnSet) -> Self {
        Self { columns }
    }
}

/// Write column name : col.name if non empty, else head[col.num]
pub fn write_colname(w: &mut dyn Write, col: &OutCol, head: &StringLine) -> Result<()> {
    if col.name.is_empty() {
        w.write_all(head.get(col.num).as_bytes())?;
    } else {
        w.write_all(col.name.as_bytes())?;
    }
    Ok(())
}

impl ColumnFun for ReaderColumns {
    fn write(&mut self, w: &mut dyn Write, line: &TextLine, text: &TextFileMode) -> Result<()> {
        self.columns.write3(w, line, text)?;
        Ok(())
    }

    fn add_names(&self, w: &mut ColumnHeader, head: &StringLine) -> Result<()> {
        for x in self.columns.get_cols() {
            if x.name.is_empty() {
                w.push(head.get(x.num))?;
            } else {
                w.push(&x.name)?;
            }
        }
        Ok(())
    }
    fn lookup(&mut self, field_names: &[&str]) -> Result<()> {
        self.columns.lookup(field_names)
    }
}

/// A collection of `ColumnFun` writers
#[derive(Default)]
pub struct Writer {
    v: Vec<Box<dyn ColumnFun>>,
    text: TextFileMode,
}
impl fmt::Debug for Writer {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Writer")
    }
}

impl Writer {
    /// new Writer
    #[must_use]
    pub fn new(text: TextFileMode) -> Self {
        Self { v: Vec::new(), text }
    }
    /// is it empty
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.v.is_empty()
    }
    /// resolve column names
    pub fn lookup(&mut self, field_names: &[&str]) -> Result<()> {
        for x in &mut self.v {
            x.lookup(field_names)?;
        }
        Ok(())
    }
    /// Add a new writer
    pub fn push(&mut self, x: Box<dyn ColumnFun>) {
        self.v.push(x);
    }
    /// Write the column names
    pub fn add_names(&self, w: &mut ColumnHeader, head: &StringLine) -> Result<()> {
        for x in &self.v {
            x.add_names(w, head)?;
        }
        Ok(())
    }
    /// Write the column values
    pub fn write(&mut self, w: &mut dyn Write, line: &TextLine) -> Result<()> {
        let mut iter = self.v.iter_mut();
        match iter.next() {
            None => {}
            Some(first) => {
                first.write(w, line, &self.text)?;
                for x in iter {
                    w.write_all(&[self.text.delim])?;
                    x.write(w, line, &self.text)?;
                }
            }
        }
        w.write_all(b"\n")?;
        Ok(())
    }
}

/// a column, by name or number
#[derive(Debug, Clone, Default)]
pub struct NamedCol {
    /// the column name. Empty if using column by number
    pub name: String,
    /// the column number, either as originally set or after lookup
    pub num: usize,
    /// if non-zero, input was "+2" so num should be calculated as (`num_cols` - `from_end`)
    pub from_end: usize,
}

impl fmt::Display for NamedCol {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Column {}", self.num + 1)?;
        if !self.name.is_empty() {
            write!(f, " ({})", self.name)
        } else if self.from_end != 0 {
            write!(f, " (+{})", self.from_end)
        } else {
            Ok(())
        }
    }
}

impl NamedCol {
    /// new named column
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }
    /// new column from spec
    pub fn new_from(spec: &str) -> Result<Self> {
        let mut x = Self::default();
        let rest = x.parse(spec)?;
        if rest.is_empty() {
            Ok(x)
        } else {
            err!("Extra stuff {} at the end of column spec {}", rest, spec)
        }
    }
    /// Resolve the column name
    pub fn lookup(&mut self, field_names: &[&str]) -> Result<()> {
        if !self.name.is_empty() {
            self.num = ColumnSet::lookup_col(field_names, &self.name)?;
        } else if self.from_end > 0 {
            if self.from_end > field_names.len() {
                return err!(
                    "Requested column +{}, but there are only {} columns",
                    self.from_end,
                    field_names.len()
                );
            }
            self.num = field_names.len() - self.from_end;
        }
        Ok(())
    }
    /// Extract a column name or number, return the unused part of the slice
    pub fn parse<'a>(&mut self, orig_spec: &'a str) -> Result<&'a str> {
        let mut spec = orig_spec;
        self.num = 0;
        self.name.clear();
        if spec.is_empty() {
            return err!("Empty string found where column name expected");
        }
        let mut ch = spec.first();
        let was_plus = ch == '+';
        if was_plus {
            ch = spec.take_first();
        }
        if ch.is_ascii_digit() && ch != '0' {
            let (a, b) = spec.to_usize();
            self.num = a;
            spec = b;
            if was_plus {
                self.from_end = self.num;
            } else {
                self.num -= 1;
            }
            Ok(spec)
        } else if ch.is_alphabetic() {
            if was_plus {
                return err!("'+' must be followed by a number : {}", orig_spec);
            }
            let pos = get_col_name(spec);
            self.name.clear();
            self.name += &spec[0..pos];
            Ok(&spec[pos..])
        } else {
            err!("Bad parse of compare spec for {}", spec)
        }
    }
}

/// return number of bytes used by the column name
/// zero means no name present, return < `str.len()` if there's extra stuff
#[must_use]
pub fn get_col_name(spec: &str) -> usize {
    if spec.is_empty() {
        return 0;
    }
    let mut sp = spec;
    let mut ch = sp.take_first();
    if !ch.is_alphabetic() {
        return 0;
    }
    while !sp.is_empty() {
        ch = sp.first();
        if ch.is_alphanumeric() || ch == '_' {
            sp = sp.skip_first();
        } else {
            break;
        }
    }
    spec.len() - sp.len()
}

#[derive(Debug, Clone, Default)]
struct CompositeColumnPart {
    prefix: String,
    col: NamedCol,
}

impl CompositeColumnPart {
    fn new() -> Self {
        Self::default()
    }
    fn lookup(&mut self, field_names: &[&str]) -> Result<()> {
        self.col.lookup(field_names)
    }
}

/// Create a string from a bunch of static stings and column values
#[derive(Debug, Clone, Default)]
pub struct CompositeColumn {
    parts: Vec<CompositeColumnPart>,
    suffix: String,
    name: String,
}

impl CompositeColumn {
    /// new
    pub fn new(s: &str) -> Result<Self> {
        let mut c = Self::default();
        c.set(s)?;
        Ok(c)
    }
    /// resolve named columns
    pub fn lookup(&mut self, field_names: &[&str]) -> Result<()> {
        for x in &mut self.parts {
            x.lookup(field_names)?;
        }
        Ok(())
    }
    /// construct string from column values
    pub fn get(&self, t: &mut Vec<u8>, fields: &[&[u8]]) {
        t.clear();
        for x in &self.parts {
            t.extend(x.prefix.as_bytes());
            t.extend(fields[x.col.num]);
        }
        t.extend(self.suffix.as_bytes());
    }
    /// configure from spec
    pub fn set(&mut self, spec: &str) -> Result<()> {
        const TAG: char = '^';
        let name = spec.split_once(':');
        if name.is_none() {
            return err!("Composite Column Spec must start with ColName: : {}", spec);
        }
        let name = name.unwrap();
        self.name = name.0.to_string();
        let mut curr = name.1;
        self.suffix.clear();
        self.parts.clear();
        while !curr.is_empty() {
            let ch = curr.take_first();
            if ch == TAG {
                if curr.is_empty() {
                    self.suffix.push(TAG);
                } else if curr.first() == TAG {
                    self.suffix.push(TAG);
                    curr = curr.skip_first();
                } else {
                    let mut p = CompositeColumnPart::new();
                    std::mem::swap(&mut p.prefix, &mut self.suffix);
                    if curr.first() == '{' {
                        curr = curr.skip_first();
                        curr = p.col.parse(curr)?;
                        if curr.is_empty() || curr.first() != '}' {
                            return err!("Closing bracket not found : {}", spec);
                        }
                        curr = curr.skip_first();
                    } else {
                        curr = p.col.parse(curr)?;
                    }

                    self.parts.push(p);
                }
            } else {
                self.suffix.push(ch);
            }
        }
        Ok(())
    }
}

impl ColumnFun for CompositeColumn {
    /// write the column names (called once)
    fn add_names(&self, w: &mut ColumnHeader, _head: &StringLine) -> Result<()> {
        w.push(&self.name)
    }
    /// write the column values (called many times)
    fn write(&mut self, w: &mut dyn Write, line: &TextLine, text: &TextFileMode) -> Result<()> {
        for x in &self.parts {
            text.write(w, x.prefix.as_bytes())?;
            text.write(w, line.get(x.col.num))?;
        }
        text.write(w, self.suffix.as_bytes())?;
        Ok(())
    }
    /// resolve any named columns
    fn lookup(&mut self, field_names: &[&str]) -> Result<()> {
        Self::lookup(self, field_names)
    }
}

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

    macro_rules! assert_err {
	($expression:expr, $($pattern:tt)+) => {
            match $expression {
		$($pattern)+ => (),
		ref e => panic!("expected `{}` but got `{:?}`", stringify!($($pattern)+), e),
            }
	}
    }

    #[test]
    fn range() -> Result<()> {
        crate::util::init()?;
        let f: [&str; 5] = ["zero", "one", "two", "three", "four"];
        let res: [OutCol; 5] = [
            OutCol::from_num(0),
            OutCol::from_num(1),
            OutCol::from_num(2),
            OutCol::from_num(3),
            OutCol::from_num(4),
        ];
        assert_eq!(ColumnSet::range(&f, "(range,<p)")?, [OutCol::from_num(1), OutCol::from_num(4)]);
        assert_eq!(ColumnSet::range(&f, "2-+2")?, res[1..=3]);
        assert_eq!(ColumnSet::range(&f, "-")?, res);
        assert_eq!(ColumnSet::range(&f, "2-")?, res[1..]);
        assert_eq!(ColumnSet::range(&f, "-2")?, res[..2]);
        assert_err!(ColumnSet::range(&f, "1-2-3"), Err(_));
        Ok(())
    }

    #[test]
    fn named_range() -> Result<()> {
        crate::util::init()?;
        let f: [&str; 5] = ["zero", "one", "two", "three", "four"];
        let res: [OutCol; 5] = [
            OutCol::new(0, "stuff"),
            OutCol::new(1, "junk"),
            OutCol::new(2, "this"),
            OutCol::new(3, "that"),
            OutCol::new(4, "other"),
        ];
        assert_eq!(ColumnSet::range(&f, "stuff:1")?, res[0..1]);
        assert_eq!(ColumnSet::ranges(&f, "stuff:1,junk:2")?, res[0..2]);
        Ok(())
    }

    #[test]
    fn do_get_col_name() -> Result<()> {
        crate::util::init()?;
        assert_eq!(get_col_name(""), 0);
        assert_eq!(get_col_name("..."), 0);
        assert_eq!(get_col_name("_aaa"), 0);
        assert_eq!(get_col_name("1aaa"), 0);
        assert_eq!(get_col_name("abc"), 3);
        assert_eq!(get_col_name("abc,"), 3);
        assert_eq!(get_col_name("abc,aaa"), 3);
        assert_eq!(get_col_name("a_b_c"), 5);
        assert_eq!(get_col_name("a_ñ_c"), 6);
        Ok(())
    }
}