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
extern crate chrono;
extern crate clap;
extern crate colonnade;
extern crate ini;
extern crate regex;
extern crate term_size;
extern crate two_timer;

use crate::util::{base_dir, fatal, success, warn, Style, STYLE_MATCHER};
use chrono::{Datelike, Duration, NaiveDate};
use clap::{App, Arg, ArgMatches, SubCommand};
use colonnade::{Alignment, Colonnade};
use ini::Ini;
use regex::Regex;
use std::collections::BTreeMap;
use std::env;
use std::fs::File;
use std::path::PathBuf;
use two_timer::{parsable, parse, Config};

pub const PRECISION: &str = "2";
pub const SUNDAY_BEGINS_WEEK: &str = "true";
pub const LENGTH_PAY_PERIOD: &str = "14";
pub const DAY_LENGTH: &str = "8";
pub const BEGINNING_WORK_DAY: (usize, usize) = (9, 0);
pub const WORKDAYS: &str = "MTWHF";
pub const COLOR: &str = "true";
pub const TRUNCATION: &str = "round";
pub const CLOCK: &str = "12";
pub const STYLES: &'static [[&'static str; 4]; 10] = &[
    [
        "alert",
        "purple",
        "something salient",
        "ongoing end time in summary",
    ],
    [
        "duration",
        "green",
        "event duration in summaries",
        "summary",
    ],
    [
        "error",
        "bold red",
        "something went wrong",
        "parse-time with no time expression provided",
    ],
    [
        "even",
        "cyan",
        "even row in a striped table",
        "configure --list",
    ],
    [
        "header",
        "bold blue",
        "header row in vacation table",
        "vacation --list",
    ],
    [
        "important",
        "red",
        "important information",
        "TOTAL_HOURS in summary",
    ],
    ["odd", "", "odd row in a striped table", "configure --list"],
    [
        "success",
        "bold green",
        "everything is okay",
        "confirmation of configuration changes",
    ],
    ["tags", "blue", "tags in summaries", "summary"],
    [
        "warning",
        "bold purple",
        "something needs attention",
        "alert given by summary when previous day's final task was not closed",
    ],
];

fn after_help() -> &'static str {
    lazy_static! {
        static ref INTRO: &'static str = "\
    Set or display configuration parameters that control date interpretation, log summarization, etc. \
    Some configuration may be taken from environment variables -- VISUAL, EDITOR, NO_COLOR. \
If this is occurring, this will be explained when you list the configuration.

The ansi_term crate is used to provide the optional styling. One can find a list of the fixed color \
    values at https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit. Style specifications are parsed \
by the following grammar:

  TOP        -> spec* 

  spec       -> non_color | foreground | background
  non_color  -> \"bold\" | \"italic\" | \"underline\" | \"dimmed\" | \"blink\" | \"reverse\" | \"hidden\"
  foreground -> fg? color
  background -> bg  color
  fg         -> \"fg\" | \"foreground\"
  bg         -> \"bg\" | \"background\"
  color      -> named | fixed
  named      -> \"black\" | \"red\" | \"green\" | \"yellow\" | \"blue\" | \"purple\" | \"cyan\" | \"white\"
  fixed      -> 0 - 255

Examples:

  red
  bold dimmed bg cyan
  foreground 16

The specifiable styles and more sample style specifications can be found in the table below.

";
        static ref OUTRO: &'static str = "\
All prefixes of 'configure' are aliases of the subcommand.
";
        static ref TEXT: String = {
            let mut s = INTRO.to_string();
            s.push_str(&describe_styles());
            s.push_str("\n");
            s.push_str(&OUTRO);
            s
        };
    }
    &TEXT
}

fn describe_styles() -> String {
    let mut data = vec![["IDENTIFIER", "DEFAULT STYLE", "DESCRIPTION", "EXAMPLE"]
        .iter()
        .map(|s| s.to_string())
        .collect::<Vec<_>>()];
    for row in STYLES {
        data.push(row.iter().map(|s| s.to_string()).collect());
    }
    let max_width = term_size::dimensions().unwrap_or((100, 0)).0;
    let width = if max_width > 100 { 100 } else { max_width };
    let mut colonnade = Colonnade::new(4, width).expect("could not tabulate styles");
    colonnade
        .spaces_between_rows(1)
        .padding_left(2)
        .expect("insufficient space to tabulate styles");
    colonnade.columns[0].priority(0);
    colonnade.columns[1].priority(0);
    colonnade.columns[2].priority(1);
    colonnade.columns[3].priority(1);
    colonnade
        .tabulate(data)
        .expect("could not tabulate data")
        .join("\n")
        + "\n"
}

fn valid_length_pay_period(v: String) -> Result<(), String> {
    let n = v.parse::<u32>();
    if n.is_ok() {
        let n = n.unwrap();
        if n > 0 {
            Ok(())
        } else {
            Err(format!("a pay period must have some positive length"))
        }
    } else {
        Err(format!("some (small) whole number of days expected"))
    }
}

fn valid_day_length(v: String) -> Result<(), String> {
    let n = v.parse::<f32>();
    if n.is_ok() {
        let n = n.unwrap();
        if n > 0.0 {
            if n > 24.0 {
                Err(format!("one cannot work more than 24 hours in a day"))
            } else {
                Ok(())
            }
        } else {
            Err(format!("a positive number of hours expected"))
        }
    } else {
        Err(format!("some (small) number of hours expected"))
    }
}

fn valid_max_width(v: String) -> Result<(), String> {
    let n = v.parse::<usize>();
    if n.is_ok() {
        if n.unwrap() < 40 {
            Err(format!(
                "summaries in fewer than 40 columns will be unreadable"
            ))
        } else {
            Ok(())
        }
    } else {
        Err(format!("some whole number of columns expected"))
    }
}

fn valid_beginning_work_day(v: String) -> Result<(), String> {
    let rx = Regex::new(r"\A([1-9]\d?)(?::([0-6]\d))?\z").unwrap();
    if let Some(captures) = rx.captures(&v) {
        let hour = captures[1].to_owned();
        let hour = hour.parse::<usize>().unwrap();
        if hour < 24 {
            if let Some(m) = captures.get(2) {
                let minute = m.as_str().parse::<usize>().unwrap();
                if minute < 60 {
                    Ok(())
                } else {
                    Err(format!(
                        "minute in beginning work day expression '{}' must be less than 60",
                        v
                    ))
                }
            } else {
                Ok(())
            }
        } else {
            Err(format!(
                "hour in beginning work day expression '{}' must be less than 24",
                v
            ))
        }
    } else {
        Err(String::from(""))
    }
}

pub fn cli(mast: App<'static, 'static>, display_order: usize) -> App<'static, 'static> {
    mast.subcommand(
        SubCommand::with_name("configure")
            .aliases(&["c", "co", "con", "conf", "confi", "config", "configu", "configur"])
            .about("Sets or displays configuration parameters")
            .after_help(after_help())
            // NOTE I'm not using default_value here so we can identify when the user misuses the subcommand and should be prompted
            .arg(
                Arg::with_name("precision") // remember to keep in sync with option in summary
                .long("precision")
                .help("Sets decimal places of precision in display of time; default value: 2")
                .long_help("The number of decimal places of precision used in the display of lengths of periods in numbers of hours. \
                If the number is 0, probably not what you want, all periods will be rounded to a whole number of hours. \
                The default value is 2. If the precision is a fraction like 'quarter' times will be rounded to the closest fraction that size of the hour for display.")
                .possible_values(&["0", "1", "2", "3", "half", "third", "quarter", "sixth", "twelfth", "sixtieth"])
                .value_name("precision")
            )
            .arg(
                Arg::with_name("truncation") // remember to keep in sync with option in summary
                .long("truncation")
                .help("Sets how fractional parts of a duration too small to display for the given precision are handled; default value: round")
                .long_help("When an events duration is displayed, there is generally some amount of information not \
                displayed given the precision. By default this portion is rounded, so if the precision is a quarter \
                hour and the duration is 7.5 minutes, this will be displayed as 0.25 hours. Alternatively, one could \
                use the floor, in which case this would be 0.00 hours, or the ceiling, in which case even a single \
                second task would be shown as taking 0.25 hours.")
                .possible_values(&["round", "floor", "ceiling"])
                .value_name("function")
            )
            .arg(
                Arg::with_name("start-pay-period")
                .long("start-pay-period")
                .help("Sets the first day of some pay period")
                .long_help("A day relative to which all pay periods will be calculated. See --length-pay-period.")
                .validator(|v| if parsable(&v) {Ok(())} else {Err(format!("cannot parse '{}' as a time expression", v))} )
                .value_name("date")
            )
            .arg(
                Arg::with_name("sunday-begins-week")
                .long("sunday-begins-week")
                .help("Sets whether Sunday should be considered the first day of the week; default value; true")
                .possible_values(&["true", "false"])
                .value_name("bool")
            )
            .arg(
                Arg::with_name("clock")
                .long("clock")
                .help("Sets times should be displayed with a 12-hour or a 24-hour clock; default value; 12")
                .possible_values(&["12", "24"])
                .value_name("type")
            )
            .arg(
                Arg::with_name("length-pay-period")
                .long("length-pay-period")
                .help("Sets the number of days in a pay period; default value: 14")
                .validator(valid_length_pay_period)
                .value_name("int")
            )
            .arg(
                Arg::with_name("day-length")
                .long("day-length")
                .help("Sets expected number of hours in a workday; default value: 8")
                .validator(valid_day_length)
                .value_name("num")
            )
            .arg(
                Arg::with_name("beginning-work-day")
                .long("beginning-work-day")
                .help("Sets when a work day typically begins; default value: 9:00")
                .validator(valid_beginning_work_day)
                .value_name("hours[:minutes]")
            )
            .arg(
                Arg::with_name("workdays")
                .long("workdays")
                .help("Sets which days you are expected to work; default value: MTWHF")
                .long_help("Workdays during the week represented as a subset of SMTWHFA, where S is Sunday and A is Saturday, etc. Default value: MTWHF.")
                .validator(|v| if Regex::new(r"\A[SMTWHFA]+\z").unwrap().is_match(&v) {Ok(())} else {Err(format!("must contain only the letters SMTWHFA, \
                where S means Sunday and A, Saturday, etc."))})
                .value_name("days")
            )
            .arg(
                Arg::with_name("editor")
                .long("editor")
                .help("Sets text editor to use when manually editing the log")
                .long_help("A text editor that the edit command will invoke. E.g., /usr/bin/vim. \
                If no editor is set, job falls back to the environment variables VISUAL and EDITOR in that order. \
                If there is still no editor, you cannot use the edit command to edit the log. \
                Note, whatever editor you use must be invocable from the shell as <editor> <file>. \
                If you need to pass additional arguments to the executable, provide them delimited by spaces \
                in the same argument. E.g., --editor='/usr/bin/open -W -n -t'")
                .value_name("path")
            )
            .arg(
                Arg::with_name("max-width")
                .long("max-width")
                .help("Sets maximum number of columns when summarizing data")
                .validator(valid_max_width)
                .value_name("num")
            )
            .arg(
                Arg::with_name("color")
                .long("color")
                .help("Sets whether to use colors; default value: true")
                .long_help("Color variation helps one parse information quickly, but if you don't want it, \
                or the ANSI color codes that produce it cause you trouble, you can turn it off. \
                If you haven't set this parameter and you don't have the NO_COLOR environment variable, Job Log will use color.")
                .possible_values(&["true", "false"])
                .value_name("bool")
            )
            .arg(
                Arg::with_name("style")
                .long("style")
                .help("Sets the style for a particular style identifier")
                .long_help("Sets the style for a particular style identifier. E.g., --style header 'bold italic purple'")
                .value_name("id spec")
                .multiple(true)
                .number_of_values(2)
            )
            .arg(
                Arg::with_name("budget")
                .short("b")
                .long("budget")
                .help("Sets the time budget for a particular tag")
                .long_help("Sets the time budget within the pay period for a particular tag. See the \"when\" command. \
                E.g., --budget foo 12.5")
                .value_name("tag hours")
                .multiple(true)
                .number_of_values(2)
            )
            .arg(
                Arg::with_name("unset")
                .short("u")
                .long("unset")
                .help("Returns a configurable parameter to its default; to unset styles you need to provide both \
                'style' and the parameter you wish to unset; e.g., --unset 'style even'. \
                Likewise for time budgets you need to provide both 'budget' and a tag identifying a particular \
                budget; e.g., --unset 'budget foo'")
                .value_name("param")
                .multiple(true)
                .number_of_values(1)
            )
            .arg(
                Arg::with_name("list")
                .short("l")
                .long("list")
                .help("Lists all configuration parameters")
                .long_help("List all configuration parameters and their values.")
            )
            .display_order(display_order)
    )
}

pub fn run(directory: Option<&str>, matches: &ArgMatches) {
    let mut did_something = false;
    let mut write = false;
    let mut conf = Configuration::read(None, directory);
    if let Some(v) = matches.value_of("start-pay-period") {
        did_something = true;
        let tt_conf = Config::new()
            .monday_starts_week(!conf.sunday_begins_week)
            .pay_period_length(conf.length_pay_period)
            .pay_period_start(conf.start_pay_period);
        let (start_date_time, _, _) = parse(v, Some(tt_conf)).unwrap();
        let year = start_date_time.year();
        let month = start_date_time.month();
        let day = start_date_time.day();
        let start_date = NaiveDate::from_ymd(year, month, day);
        if conf.start_pay_period.is_some() && &start_date == conf.start_pay_period.as_ref().unwrap()
        {
            warn(
                format!("start-pay-period is already {} {} {}!", year, month, day),
                &conf,
            );
        } else {
            println!("setting start-pay-period to {} {} {}!", year, month, day);
            conf.start_pay_period = Some(start_date);
            write = true;
        }
    }
    if matches.is_present("sunday-begins-week") {
        did_something = true;
        if let Some(v) = matches.value_of("sunday-begins-week") {
            let v: bool = v.parse().unwrap();
            if v == conf.sunday_begins_week {
                warn(format!("sunday-begins-week is already {}!", v), &conf);
            } else {
                success(format!("setting sunday-begins-week to {}!", v), &conf);
                conf.sunday_begins_week = v;
                write = true;
            }
        }
    }
    if matches.is_present("clock") {
        did_something = true;
        if let Some(v) = matches.value_of("clock") {
            if (v == CLOCK) == conf.h12 {
                warn(format!("clock is already {}!", v), &conf);
            } else {
                success(format!("setting clock to {}!", v), &conf);
                conf.h12 = v == CLOCK;
                write = true;
            }
        }
    }
    if matches.is_present("color") {
        did_something = true;
        if let Some(v) = matches.value_of("color") {
            let v: bool = v.parse().unwrap();
            conf.color = Some(v);
            // demonstrate that we've set the color
            success(format!("set color to {}!", v), &conf);
            write = true;
        }
    }
    if matches.is_present("length-pay-period") {
        did_something = true;
        if let Some(v) = matches.value_of("length-pay-period") {
            let v: u32 = v.parse().unwrap();
            if v == conf.length_pay_period {
                warn(format!("length-pay-period is already {}!", v), &conf);
            } else {
                success(format!("setting length-pay-period to {}!", v), &conf);
                conf.length_pay_period = v;
                write = true;
            }
        }
    }
    if matches.is_present("beginning-work-day") {
        did_something = true;
        let v = matches.value_of("beginning-work-day").unwrap();
        let rx = Regex::new(r"\A(\d+)(?::0*(\d+))?\z").unwrap();
        let captures = rx.captures(&v).unwrap();
        let hour = captures[1].parse::<usize>().unwrap();
        let minute = if let Some(m) = captures.get(2) {
            m.as_str().parse::<usize>().unwrap()
        } else {
            0
        };
        let beginning_work_day = (hour, minute);
        if conf.beginning_work_day == beginning_work_day {
            warn(
                format!("beginning-work-day is already {}:{:02}!", hour, minute),
                &conf,
            );
        } else {
            success(
                format!("setting beginning-work-day to {}:{:02}!", hour, minute),
                &conf,
            );
            conf.beginning_work_day = beginning_work_day;
            write = true;
        }
    }
    if matches.is_present("day-length") {
        did_something = true;
        if let Some(v) = matches.value_of("day-length") {
            let v: f32 = v.parse().unwrap();
            if v == conf.day_length {
                warn(format!("day-length is already {}!", v), &conf);
            } else {
                success(format!("setting day-length to {}!", v), &conf);
                conf.day_length = v;
                write = true;
            }
        }
    }
    if matches.is_present("precision") {
        did_something = true;
        if let Some(v) = matches.value_of("precision") {
            let v = Precision::from_s(v);
            if v == conf.precision {
                warn(format!("precision is already {}!", v.to_s()), &conf);
            } else {
                success(format!("setting precision to {}!", v.to_s()), &conf);
                conf.precision = v;
                write = true;
            }
        }
    }
    if matches.is_present("truncation") {
        did_something = true;
        if let Some(v) = matches.value_of("truncation") {
            let v = Truncation::from_s(v);
            if v == conf.truncation {
                warn(format!("truncation is already {}!", v.to_s()), &conf);
            } else {
                success(format!("setting truncation to {}!", v.to_s()), &conf);
                conf.truncation = v;
                write = true;
            }
        }
    }
    if matches.is_present("workdays") {
        did_something = true;
        if let Some(v) = matches.value_of("workdays") {
            if v == &conf.serialize_workdays() {
                warn(format!("workdays is already {}!", v), &conf);
            } else {
                success(format!("setting workdays to {}!", v), &conf);
                conf.workdays(v);
                write = true;
            }
        }
    }
    if let Some(v) = matches.value_of("editor") {
        did_something = true;
        if conf.editor.is_some() && v == conf.editor.as_ref().unwrap().join(" ") {
            warn(format!("editor is already {}!", v), &conf);
        } else {
            success(format!("setting editor to {}!", v), &conf);
            conf.editor(v);
            write = true;
        }
    }
    if let Some(v) = matches.value_of("max-width") {
        did_something = true;
        let v = v.parse::<usize>().unwrap();
        if conf.max_width.is_some() && v == conf.max_width.unwrap() {
            warn(format!("max-width is already {}!", v), &conf);
        } else {
            success(format!("setting max-width to {}!", v), &conf);
            conf.max_width = Some(v);
            write = true;
        }
    }
    if let Some(vs) = matches.values_of("style") {
        let values = vs.map(|s| s.to_string()).collect::<Vec<_>>();
        for v in values.windows(2) {
            let identifier = v[0].clone();
            let style = v[1].clone();
            if !STYLE_MATCHER.is_match(&style) {
                fatal(
                    format!("cannot parse \"{}\" as a style specification", style),
                    &conf,
                );
            }
            if conf.style_map.contains_key(&identifier) {
                conf.style_map.insert(identifier, style);
            } else {
                fatal(
                    format!("there is no configurable style named '{}'", identifier),
                    &conf,
                );
            }
            success(format!("set {} to {}", v[0], v[1]), &conf);
            did_something = true;
            write = true;
        }
    }
    if let Some(vs) = matches.values_of("budget") {
        if let Some(total_hours) = conf.hours_in_pay_period() {
            if total_hours == 0.0 {
                fatal(
                    "cannot set time budgets if there are no expected work hours in pay period"
                        .to_owned(),
                    &conf,
                );
            } else {
                let mut budgets: Vec<(String, f32)> = conf
                    .budgets
                    .clone()
                    .or_else(|| Some(vec![]))
                    .unwrap()
                    .iter()
                    .map(|(tag, hours)| (tag.clone(), hours.clone()))
                    .collect();
                let values = vs.map(|s| s.to_string()).collect::<Vec<_>>();
                for v in values.windows(2) {
                    let tag = v[0].clone();
                    let hours = v[1].clone();
                    if let Ok(h) = hours.parse::<f32>() {
                        if let Some(pair) = budgets.iter_mut().find(|p| p.0 == tag) {
                            pair.1 = h;
                        } else {
                            budgets.push((tag, h))
                        }
                        success(
                            format!("set time budget for \"{}\" to {} hours", v[0], v[1]),
                            &conf,
                        );
                        did_something = true;
                        write = true;
                    } else {
                        fatal(
                            format!("cannot parse \"{}\" as a number of hours", hours),
                            &conf,
                        );
                    }
                }
                let budgeted_hours: f32 = budgets.iter().map(|p| p.1).sum();
                conf.budgets = Some(budgets);
                if budgeted_hours > total_hours {
                    warn(
                        format!(
                            "hours budgeted: {}; hours in pay period: {}",
                            budgeted_hours, total_hours
                        ),
                        &conf,
                    )
                }
            }
        } else {
            fatal(
                "cannot set time budgets without an established pay period".to_owned(),
                &conf,
            )
        }
    }
    if let Some(vs) = matches.values_of("unset") {
        for v in vs {
            did_something = true;
            let mut set = true;
            let mut warning = None;
            match v {
                "day-length" => {
                    conf.day_length = DAY_LENGTH.parse().unwrap();
                    write = true;
                }
                "editor" => {
                    conf.editor = None;
                    write = true;
                }
                "color" => {
                    conf.color = None;
                    write = true;
                }
                "clock" => {
                    conf.h12 = "12" == CLOCK;
                    write = true;
                }
                "length-pay-period" => {
                    conf.length_pay_period = LENGTH_PAY_PERIOD.parse().unwrap();
                    write = true;
                }
                "max-width" => {
                    conf.max_width = None;
                    write = true;
                }
                "precision" => {
                    conf.precision = Precision::from_s(PRECISION);
                    write = true;
                }
                "truncation" => {
                    conf.truncation = Truncation::from_s(TRUNCATION);
                    write = true;
                }
                "start-pay-period" => {
                    conf.start_pay_period = None;
                    write = true;
                }
                "sunday-begins-week" => {
                    conf.sunday_begins_week = SUNDAY_BEGINS_WEEK.parse().unwrap();
                    write = true;
                }
                "workdays" => {
                    conf.workdays(WORKDAYS);
                    write = true;
                }
                _ => {
                    let parts = v.split_whitespace().collect::<Vec<_>>();
                    if parts.len() == 2 && parts[0] == "style" {
                        if conf.style_map.contains_key(parts[1]) {
                            write = true;
                            set = true;
                            conf.style_map
                                .insert(parts[1].to_owned(), default_style(parts[1]).to_owned());
                        } else {
                            warning = Some(format!("unknown style: \"{}\"", parts[1]));
                            set = false;
                        }
                    } else if parts.len() > 1 && parts[0] == "budget" {
                        let tag = parts[1..parts.len()].join(" ");
                        let mut budgets: Vec<(String, f32)> = conf
                            .budgets
                            .clone()
                            .or_else(|| Some(vec![]))
                            .unwrap()
                            .iter()
                            .map(|(tag, hours)| (tag.clone(), hours.clone()))
                            .collect();
                        if let Some(i) = budgets.iter().position(|p| {
                            p.0.split_whitespace().collect::<Vec<_>>().join(" ") == tag
                        }) {
                            write = true;
                            set = true;
                            if budgets.len() == 1 {
                                conf.budgets = None
                            } else {
                                budgets.remove(i);
                                conf.budgets = Some(budgets)
                            }
                        } else {
                            warning = Some(format!("unknown budget: \"{}\"", tag));
                            set = false
                        }
                    } else {
                        set = false
                    }
                }
            }
            if set {
                success(format!("unset {}", v), &conf);
            } else {
                warn(
                    warning.unwrap_or(format!("unknown configuration parameter: {}", v)),
                    &conf,
                );
            }
        }
    }
    if write {
        conf.write()
    }
    if matches.is_present("list") {
        let mut footnotes: Vec<String> = Vec::new();
        if did_something {
            println!("");
        } else {
            did_something = true;
        }
        let mut attributes = vec![
            vec![
                String::from("precision"),
                format!("{}", conf.precision.to_s()),
            ],
            vec![
                String::from("truncation"),
                format!("{}", conf.truncation.to_s()),
            ],
            vec![
                String::from("max-width"),
                if conf.max_width.is_some() {
                    format!("{}", conf.max_width.unwrap())
                } else {
                    String::from("")
                },
            ],
            vec![
                String::from("length-pay-period"),
                format!("{}", conf.length_pay_period),
            ],
            vec![
                String::from("start-pay-period"),
                format!(
                    "{}",
                    if conf.start_pay_period.is_some() {
                        let spp = conf.start_pay_period.unwrap();
                        format!("{} {} {}", spp.year(), spp.month(), spp.day())
                    } else {
                        String::from("")
                    }
                ),
            ],
            vec![
                String::from("sunday-begins-week"),
                format!("{}", conf.sunday_begins_week),
            ],
            vec![
                String::from("clock"),
                format!("{}", if conf.h12 { "12" } else { "24" }),
            ],
            vec![String::from("workdays"), conf.serialize_workdays()],
            vec![
                String::from("beginning-work-day"),
                format!(
                    "{}:{:02}",
                    conf.beginning_work_day.0, conf.beginning_work_day.1
                ),
            ],
            vec![String::from("day-length"), format!("{}", conf.day_length)],
            vec![String::from("editor"), {
                match conf.effective_editor() {
                    Some((editor, source)) => {
                        let mut editor = editor.join(" ");
                        if let Some(source) = source {
                            for _ in 0..footnotes.len() + 1 {
                                editor.push_str("*");
                            }
                            footnotes.push(source);
                        }
                        editor
                    }
                    _ => String::from(""),
                }
            }],
            vec![String::from("color"), {
                let (c, source) = conf.effective_color();
                let mut color = format!("{}", c);
                if let Some(source) = source {
                    for _ in 0..footnotes.len() + 1 {
                        color.push_str("*");
                    }
                    footnotes.push(source);
                }
                color
            }],
        ];
        for style in &conf.style_map {
            attributes.push(vec![style.0.clone(), style.1.clone()]);
        }
        if let Some(budgets) = &conf.budgets {
            attributes.push(vec!["time budgets".to_owned(), "".to_owned()]);
            for budget in budgets.iter() {
                attributes.push(vec![
                    format!("\u{00A0}\u{00A0}{}", budget.0),
                    format!("{}", budget.1),
                ])
            }
        }
        let mut table = Colonnade::new(2, conf.width()).unwrap();
        table.columns[1].alignment(Alignment::Right).left_margin(2);
        let style = Style::new(&conf);
        for (i, line) in table.tabulate(&attributes).unwrap().iter().enumerate() {
            if i % 2 == 1 {
                println!("{}", style.paint("even", line)) // even in a one-indexed table
            } else {
                println!("{}", style.paint("odd", line));
            }
        }
        if !footnotes.is_empty() {
            println!("\nenvironment variable sources:");
            let data: Vec<Vec<String>> = footnotes
                .into_iter()
                .enumerate()
                .map(|(i, s)| {
                    let asterisks = std::iter::repeat("*").take(i + 1).collect::<String>();
                    vec![asterisks, s]
                })
                .collect();
            table = Colonnade::new(2, conf.width()).unwrap();
            table.columns[0].alignment(Alignment::Right).left_margin(2);
            for line in table.tabulate(data).expect("data too wide") {
                println!("{}", line);
            }
        }
    }
    if !did_something {
        println!("{}", matches.usage());
    }
}

#[derive(Debug, Clone)]
pub enum Truncation {
    Round,
    Floor,
    Ceiling,
}

impl Truncation {
    fn to_s(&self) -> &str {
        match self {
            Truncation::Round => "round",
            Truncation::Floor => "floor",
            Truncation::Ceiling => "ceiling",
        }
    }
    fn from_s(s: &str) -> Truncation {
        match s {
            "round" => Truncation::Round,
            "ceiling" => Truncation::Ceiling,
            "floor" => Truncation::Floor,
            _ => unreachable!(),
        }
    }
    pub fn prepare(&self, n: f32, precision: &Precision) -> f32 {
        match self {
            Truncation::Round => match precision {
                // these ones will be taken care of by the formatter
                Precision::P0 | Precision::P1 | Precision::P2 | Precision::P3 => n,
                _ => (n * precision.multiplier()).round() / precision.multiplier(),
            },
            _ => {
                let mut n = n * precision.multiplier();
                n = match self {
                    Truncation::Ceiling => n.ceil(),
                    Truncation::Floor => n.floor(),
                    _ => unreachable!(),
                };
                n / precision.multiplier()
            }
        }
    }
}

impl PartialEq for Truncation {
    fn eq(&self, other: &Self) -> bool {
        match self {
            Truncation::Round => match other {
                Truncation::Round => true,
                _ => false,
            },
            Truncation::Floor => match other {
                Truncation::Floor => true,
                _ => false,
            },
            Truncation::Ceiling => match other {
                Truncation::Ceiling => true,
                _ => false,
            },
        }
    }
}

#[derive(Debug, Clone)]
pub enum Precision {
    P0,
    P1,
    P2,
    P3,
    Half,
    Third,
    Quarter,
    Sixth,
    Twelfth,
    Sixtieth,
}

impl Precision {
    fn to_s(&self) -> &str {
        match self {
            Precision::P0 => "0",
            Precision::P1 => "1",
            Precision::P2 => "2",
            Precision::P3 => "3",
            Precision::Half => "half",
            Precision::Third => "third",
            Precision::Quarter => "quarter",
            Precision::Sixth => "sixth",
            Precision::Twelfth => "twelfth",
            Precision::Sixtieth => "sixtieth",
        }
    }
    fn from_s(s: &str) -> Precision {
        match s {
            "0" => Precision::P0,
            "1" => Precision::P1,
            "2" => Precision::P2,
            "3" => Precision::P3,
            "half" => Precision::Half,
            "third" => Precision::Third,
            "quarter" => Precision::Quarter,
            "sixth" => Precision::Sixth,
            "twelfth" => Precision::Twelfth,
            "sixtieth" => Precision::Sixtieth,
            _ => unreachable!(),
        }
    }
    pub fn multiplier(&self) -> f32 {
        match self {
            Precision::P0 => 1.0,
            Precision::P1 => 10.0,
            Precision::P2 => 100.0,
            Precision::P3 => 1000.0,
            Precision::Half => 2.0,
            Precision::Third => 3.0,
            Precision::Quarter => 4.0,
            Precision::Sixth => 6.0,
            Precision::Twelfth => 12.0,
            Precision::Sixtieth => 60.0,
        }
    }
    pub fn precision(&self) -> usize {
        match self {
            Precision::P0 => 0,
            Precision::P1 => 1,
            Precision::P2 => 2,
            Precision::P3 => 3,
            Precision::Half => 1,
            _ => 2,
        }
    }
}

impl PartialEq for Precision {
    fn eq(&self, other: &Self) -> bool {
        match self {
            Precision::P0 => match other {
                Precision::P0 => true,
                _ => false,
            },
            Precision::P1 => match other {
                Precision::P1 => true,
                _ => false,
            },
            Precision::P2 => match other {
                Precision::P2 => true,
                _ => false,
            },
            Precision::P3 => match other {
                Precision::P3 => true,
                _ => false,
            },
            Precision::Half => match other {
                Precision::Half => true,
                _ => false,
            },
            Precision::Third => match other {
                Precision::Third => true,
                _ => false,
            },
            Precision::Quarter => match other {
                Precision::Quarter => true,
                _ => false,
            },
            Precision::Sixth => match other {
                Precision::Sixth => true,
                _ => false,
            },
            Precision::Twelfth => match other {
                Precision::Twelfth => true,
                _ => false,
            },
            Precision::Sixtieth => match other {
                Precision::Sixtieth => true,
                _ => false,
            },
        }
    }
}

#[derive(Clone)]
pub struct Configuration {
    pub day_length: f32,
    pub editor: Option<Vec<String>>,
    pub length_pay_period: u32,
    pub precision: Precision,
    pub truncation: Truncation,
    pub start_pay_period: Option<NaiveDate>,
    pub sunday_begins_week: bool,
    pub beginning_work_day: (usize, usize),
    color: Option<bool>,
    pub workdays: u8, // bit flags
    pub max_width: Option<usize>,
    dir: String,
    pub h12: bool,
    pub style_map: BTreeMap<String, String>,
    pub budgets: Option<Vec<(String, f32)>>,
}

fn default_style(identifier: &str) -> &'static str {
    let row = STYLES
        .iter()
        .find(|r| r[0] == identifier)
        .expect(&format!("there is no {} style", identifier));
    row[1]
}

impl Configuration {
    fn max_term_size() -> usize {
        term_size::dimensions().unwrap_or((80, 0)).0 // if term_size fails us, use a default of 80
    }
    // the minimum of the current terminal width or the configured width, if any
    pub fn width(&self) -> usize {
        let t = Configuration::max_term_size();
        if self.max_width.is_some() {
            let n = self.max_width.unwrap();
            if n > t {
                t
            } else {
                n
            }
        } else {
            t
        }
    }
    // option parameter facilitates testing
    pub fn read(path: Option<PathBuf>, directory: Option<&str>) -> Configuration {
        let path = path.unwrap_or(Configuration::config_file(directory));
        if !path.as_path().exists() {
            File::create(path.to_str().unwrap()).expect(&format!(
                "could not create configuration file {}",
                path.to_str().unwrap()
            ));
        }
        let directory = path
            .as_path()
            .canonicalize()
            .expect(&format!(
                "could not canonicalize the path {}",
                path.as_path().to_str().unwrap()
            ))
            .parent()
            .unwrap()
            .to_str()
            .unwrap()
            .to_owned();
        if let Ok(ini) = Ini::load_from_file(path.as_path()) {
            let editor = if let Some(s) = ini.get_from(Some("external"), "editor") {
                Some(s.split_whitespace().map(|s| s.to_owned()).collect())
            } else {
                None
            };
            let color = if let Some(s) = ini.get_from(Some("color"), "color") {
                Some(s == COLOR)
            } else {
                None
            };
            let start_pay_period = if let Some(s) = ini.get_from(Some("time"), "start-pay-period") {
                let parts = s.split(" ").collect::<Vec<&str>>();
                Some(NaiveDate::from_ymd(
                    parts[0].parse().unwrap(),
                    parts[1].parse().unwrap(),
                    parts[2].parse().unwrap(),
                ))
            } else {
                None
            };
            let beginning_work_day = if let Some(s) =
                ini.get_from(Some("time"), "beginning-work-day")
            {
                let parts: Vec<usize> = s.split(":").map(|s| s.parse::<usize>().unwrap()).collect();
                (parts[0], parts[1])
            } else {
                BEGINNING_WORK_DAY.clone()
            };
            let mut map = BTreeMap::new();
            for style in STYLES {
                map.insert(
                    style[0].to_owned(),
                    ini.get_from_or(Some("style"), style[0], style[1])
                        .to_string(),
                );
            }
            Configuration {
                beginning_work_day,
                day_length: ini
                    .get_from_or(Some("time"), "day-length", DAY_LENGTH)
                    .parse()
                    .unwrap(),
                editor: editor,
                length_pay_period: ini
                    .get_from_or(Some("time"), "pay-period-length", LENGTH_PAY_PERIOD)
                    .parse()
                    .unwrap(),
                precision: Precision::from_s(ini.get_from_or(
                    Some("summary"),
                    "precision",
                    PRECISION,
                )),
                truncation: Truncation::from_s(ini.get_from_or(
                    Some("summary"),
                    "truncation",
                    TRUNCATION,
                )),
                start_pay_period: start_pay_period,
                sunday_begins_week: ini.get_from_or(
                    Some("time"),
                    "sunday-begins-week",
                    SUNDAY_BEGINS_WEEK,
                ) == "true",
                h12: ini.get_from_or(Some("summary"), "clock", CLOCK) == "12",
                color: color,
                workdays: Configuration::parse_workdays(ini.get_from_or(
                    Some("time"),
                    "workdays",
                    WORKDAYS,
                )),
                max_width: ini
                    .get_from(Some("summary"), "max-width")
                    .and_then(|s| Some(s.parse().unwrap())),
                dir: directory,
                style_map: map,
                budgets: ini
                    .section(Some("budget"))
                    .and_then(|p| {
                        Some(
                            p.iter()
                                .map(|(key, value)| {
                                    (String::from(key), value.parse::<f32>().unwrap())
                                })
                                .collect(),
                        )
                    })
                    .or_else(|| None),
            }
        } else {
            Configuration::defaults(directory)
        }
    }
    // factored out to facilitate testing
    fn defaults(directory: String) -> Configuration {
        let mut map = BTreeMap::new();
        for style in STYLES {
            map.insert(style[0].to_owned(), style[1].to_owned());
        }
        Configuration {
            day_length: DAY_LENGTH.parse().unwrap(),
            editor: None,
            length_pay_period: LENGTH_PAY_PERIOD.parse().unwrap(),
            beginning_work_day: BEGINNING_WORK_DAY.clone(),
            precision: Precision::from_s(PRECISION),
            truncation: Truncation::from_s(TRUNCATION),
            start_pay_period: None,
            color: None,
            sunday_begins_week: SUNDAY_BEGINS_WEEK == "true",
            workdays: Configuration::parse_workdays(WORKDAYS),
            max_width: None,
            dir: directory,
            h12: CLOCK == "12",
            style_map: map,
            budgets: None,
        }
    }
    pub fn write(&self) {
        let mut ini = Ini::new();
        if self.day_length != DAY_LENGTH.parse::<f32>().unwrap() {
            ini.with_section(Some("time"))
                .set("day-length", format!("{}", self.day_length));
        }
        if self.beginning_work_day != BEGINNING_WORK_DAY {
            ini.with_section(Some("time")).set(
                "beginning-work-day",
                format!(
                    "{}:{}",
                    self.beginning_work_day.0, self.beginning_work_day.1
                ),
            );
        }
        if let Some(s) = self.editor.as_ref() {
            let s = s.join(" ");
            ini.with_section(Some("external")).set("editor", s);
        }
        if self.length_pay_period != LENGTH_PAY_PERIOD.parse::<u32>().unwrap() {
            ini.with_section(Some("time"))
                .set("pay-period-length", format!("{}", self.length_pay_period));
        }
        if self.precision != Precision::from_s(PRECISION) {
            ini.with_section(Some("summary"))
                .set("precision", format!("{}", self.precision.to_s()));
        }
        if self.truncation != Truncation::from_s(TRUNCATION) {
            ini.with_section(Some("summary"))
                .set("truncation", format!("{}", self.truncation.to_s()));
        }
        if self.start_pay_period.is_some() {
            let spp = self.start_pay_period.unwrap();
            ini.with_section(Some("time")).set(
                "start-pay-period",
                format!("{} {} {}", spp.year(), spp.month(), spp.day()),
            );
        }
        if self.sunday_begins_week != SUNDAY_BEGINS_WEEK.parse::<bool>().unwrap() {
            ini.with_section(Some("time"))
                .set("sunday-begins-week", format!("{}", self.sunday_begins_week));
        }
        if self.h12 != (CLOCK == "12") {
            ini.with_section(Some("summary"))
                .set("clock", format!("{}", if self.h12 { "12" } else { "24" }));
        }
        if let Some(c) = self.color {
            ini.with_section(Some("color"))
                .set("color", format!("{}", c));
        }
        let s = self.serialize_workdays();
        if s != WORKDAYS {
            ini.with_section(Some("time")).set("workdays", s);
        }
        if self.max_width.is_some() {
            ini.with_section(Some("summary"))
                .set("max-width", format!("{}", self.max_width.unwrap()));
        }
        for style in &self.style_map {
            if style.1 != default_style(&style.0) {
                ini.with_section(Some("style")).set(style.0, style.1);
            }
        }
        if let Some(budgets) = &self.budgets {
            for pair in budgets {
                ini.with_section(Some("budget"))
                    .set(pair.0.clone(), format!("{}", pair.1));
            }
        }
        ini.write_to_file(Configuration::config_file(Some(&self.dir)))
            .expect("could not write config.ini");
    }
    pub fn directory(&self) -> Option<&str> {
        Some(&self.dir)
    }
    // public for testing purposes
    pub fn workdays(&mut self, workdays: &str) {
        self.workdays = Configuration::parse_workdays(workdays);
    }
    fn editor(&mut self, editor: &str) {
        self.editor = Some(editor.split_whitespace().map(|s| s.to_owned()).collect());
    }
    // returns value and its environment variable source, if any
    pub fn effective_editor(&self) -> Option<(Vec<String>, Option<String>)> {
        if let Some(vec) = self.editor.clone() {
            Some((vec, None))
        } else {
            let mut var = String::from("VISUAL");
            match env::var(&var) {
                Ok(s) => Some((
                    s.split_whitespace().map(|s| s.to_owned()).collect(),
                    Some(var),
                )),
                _ => {
                    var = String::from("EDITOR");
                    match env::var(&var) {
                        Ok(s) => Some((
                            s.split_whitespace().map(|s| s.to_owned()).collect(),
                            Some(var),
                        )),
                        _ => None,
                    }
                }
            }
        }
    }
    pub fn effective_color(&self) -> (bool, Option<String>) {
        if let Some(c) = self.color {
            (c, None)
        } else {
            let var = String::from("NO_COLOR");
            match env::var(&var) {
                Ok(_) => (false, Some(var)),
                _ => (COLOR == "true", None),
            }
        }
    }
    pub fn config_file(directory: Option<&str>) -> PathBuf {
        let mut path = base_dir(directory);
        path.push("config.ini");
        path
    }
    fn parse_workdays(serialized: &str) -> u8 {
        let mut workdays: u8 = 0;
        for c in serialized.chars() {
            if let Some(i) = "SMTWHFA".chars().position(|c2| c2 == c) {
                workdays = workdays | (1 << i);
            }
        }
        workdays
    }
    fn serialize_workdays(&self) -> String {
        let mut s = String::new();
        for (i, c) in "SMTWHFA".chars().enumerate() {
            if (1 << i) & self.workdays > 0 {
                s.push(c);
            }
        }
        s
    }
    pub fn is_workday(&self, date: &NaiveDate) -> bool {
        let i = (date.weekday().number_from_sunday() - 1) as u8;
        self.workdays & (1 << i) > 0
    }
    // find the first pay period start date *after* the given date
    pub fn next_start_pay_period(&self, date: &NaiveDate) -> Option<NaiveDate> {
        if let Some(known_pay_period_start_date) = self.start_pay_period {
            let delta = date
                .signed_duration_since(known_pay_period_start_date)
                .num_days();
            let l = self.length_pay_period as i64;
            let remainder = delta % l;
            if remainder < 0 {
                Some(date.clone() - Duration::days(remainder))
            } else {
                Some(date.clone() + Duration::days(l - remainder))
            }
        } else {
            None
        }
    }
    pub fn hours_in_pay_period(&self) -> Option<f32> {
        if let Some(d) = self.start_pay_period {
            let mut acc: f32 = 0.0;
            let mut d = d.clone();
            for _ in 0..self.length_pay_period {
                if self.is_workday(&d) {
                    acc += self.day_length;
                }
                d += Duration::days(1)
            }
            Some(acc)
        } else {
            None
        }
    }
    pub fn two_timer_config(&self) -> Option<Config> {
        Some(
            Config::new()
                .monday_starts_week(!self.sunday_begins_week)
                .pay_period_start(self.start_pay_period)
                .pay_period_length(self.length_pay_period),
        )
    }
    pub fn set_precision(&mut self, identifier: &str) {
        self.precision = Precision::from_s(identifier);
    }
    pub fn set_truncation(&mut self, identifier: &str) {
        self.truncation = Truncation::from_s(identifier);
    }
}

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

    #[test]
    fn round_quarter() {
        let trunctation = Truncation::Round;
        let precision = Precision::Quarter;
        assert_eq!(0.0, trunctation.prepare(0.0, &precision));
        assert_eq!(0.0, trunctation.prepare(0.11, &precision));
        assert_eq!(0.25, trunctation.prepare(0.125, &precision));
        assert_eq!(0.25, trunctation.prepare(0.26, &precision));
    }

    #[test]
    fn floor_quarter() {
        let trunctation = Truncation::Floor;
        let precision = Precision::Quarter;
        assert_eq!(0.0, trunctation.prepare(0.0, &precision));
        assert_eq!(0.0, trunctation.prepare(0.11, &precision));
        assert_eq!(0.0, trunctation.prepare(0.125, &precision));
        assert_eq!(0.25, trunctation.prepare(0.25, &precision));
        assert_eq!(0.25, trunctation.prepare(0.26, &precision));
    }

    #[test]
    fn ceiling_quarter() {
        let trunctation = Truncation::Ceiling;
        let precision = Precision::Quarter;
        assert_eq!(0.0, trunctation.prepare(0.0, &precision));
        assert_eq!(0.25, trunctation.prepare(0.11, &precision));
        assert_eq!(0.25, trunctation.prepare(0.125, &precision));
        assert_eq!(0.25, trunctation.prepare(0.25, &precision));
        assert_eq!(0.5, trunctation.prepare(0.26, &precision));
    }

    #[test]
    fn floor_p0() {
        let trunctation = Truncation::Floor;
        let precision = Precision::P0;
        assert_eq!(0.0, trunctation.prepare(0.0, &precision));
        assert_eq!(0.0, trunctation.prepare(0.9, &precision));
        assert_eq!(1.0, trunctation.prepare(1.0, &precision));
        assert_eq!(1.0, trunctation.prepare(1.9, &precision));
    }

    #[test]
    fn ceiling_p0() {
        let trunctation = Truncation::Ceiling;
        let precision = Precision::P0;
        assert_eq!(0.0, trunctation.prepare(0.0, &precision));
        assert_eq!(1.0, trunctation.prepare(0.11, &precision));
        assert_eq!(1.0, trunctation.prepare(1.0, &precision));
        assert_eq!(2.0, trunctation.prepare(1.1, &precision));
    }

    #[test]
    fn floor_p1() {
        let trunctation = Truncation::Floor;
        let precision = Precision::P1;
        assert_eq!(0.0, trunctation.prepare(0.0, &precision));
        assert_eq!(0.0, trunctation.prepare(0.09, &precision));
        assert_eq!(0.1, trunctation.prepare(0.1, &precision));
        assert_eq!(0.1, trunctation.prepare(0.19, &precision));
    }

    #[test]
    fn ceiling_p1() {
        let trunctation = Truncation::Ceiling;
        let precision = Precision::P1;
        assert_eq!(0.0, trunctation.prepare(0.0, &precision));
        assert_eq!(0.1, trunctation.prepare(0.011, &precision));
        assert_eq!(0.1, trunctation.prepare(0.1, &precision));
        assert_eq!(0.2, trunctation.prepare(0.11, &precision));
    }

    #[test]
    fn floor_p2() {
        let trunctation = Truncation::Floor;
        let precision = Precision::P2;
        assert_eq!(0.0, trunctation.prepare(0.0, &precision));
        assert_eq!(0.0, trunctation.prepare(0.009, &precision));
        assert_eq!(0.01, trunctation.prepare(0.01, &precision));
        assert_eq!(0.01, trunctation.prepare(0.019, &precision));
    }

    #[test]
    fn ceiling_p2() {
        let trunctation = Truncation::Ceiling;
        let precision = Precision::P2;
        assert_eq!(0.0, trunctation.prepare(0.0, &precision));
        assert_eq!(0.01, trunctation.prepare(0.0011, &precision));
        assert_eq!(0.01, trunctation.prepare(0.01, &precision));
        assert_eq!(0.02, trunctation.prepare(0.011, &precision));
    }

    #[test]
    fn floor_p3() {
        let trunctation = Truncation::Floor;
        let precision = Precision::P3;
        assert_eq!(0.0, trunctation.prepare(0.0, &precision));
        assert_eq!(0.0, trunctation.prepare(0.0009, &precision));
        assert_eq!(0.001, trunctation.prepare(0.001, &precision));
        assert_eq!(0.001, trunctation.prepare(0.0019, &precision));
    }

    #[test]
    fn ceiling_p3() {
        let trunctation = Truncation::Ceiling;
        let precision = Precision::P3;
        assert_eq!(0.0, trunctation.prepare(0.0, &precision));
        assert_eq!(0.001, trunctation.prepare(0.00011, &precision));
        assert_eq!(0.001, trunctation.prepare(0.001, &precision));
        assert_eq!(0.002, trunctation.prepare(0.0011, &precision));
    }

    #[test]
    fn next_start_pay_period_same() {
        let mut c = Configuration::defaults("foo".to_owned());
        let start_pp = NaiveDate::from_ymd(2022, 5, 15);
        let date = start_pp.clone();
        c.start_pay_period = Some(start_pp.clone());
        c.length_pay_period = 7;
        assert_eq!(
            date + Duration::days(7),
            c.next_start_pay_period(&date).unwrap()
        )
    }

    #[test]
    fn next_start_pay_period_after() {
        let mut c = Configuration::defaults("foo".to_owned());
        let start_pp = NaiveDate::from_ymd(2022, 5, 15);
        let date = start_pp + Duration::days(1);
        c.start_pay_period = Some(start_pp.clone());
        c.length_pay_period = 7;
        assert_eq!(
            date + Duration::days(6),
            c.next_start_pay_period(&date).unwrap()
        )
    }

    #[test]
    fn next_start_pay_period_before() {
        let mut c = Configuration::defaults("foo".to_owned());
        let start_pp = NaiveDate::from_ymd(2022, 5, 15);
        let date = start_pp - Duration::days(1);
        c.start_pay_period = Some(start_pp.clone());
        c.length_pay_period = 7;
        assert_eq!(
            date + Duration::days(1),
            c.next_start_pay_period(&date).unwrap()
        )
    }

    #[test]
    fn next_start_pay_period_long_after() {
        let mut c = Configuration::defaults("foo".to_owned());
        let start_pp = NaiveDate::from_ymd(2022, 5, 15);
        let date = start_pp + Duration::days(15);
        c.start_pay_period = Some(start_pp.clone());
        c.length_pay_period = 7;
        assert_eq!(
            date + Duration::days(6),
            c.next_start_pay_period(&date).unwrap()
        )
    }

    #[test]
    fn next_start_pay_period_long_before() {
        let mut c = Configuration::defaults("foo".to_owned());
        let start_pp = NaiveDate::from_ymd(2022, 5, 15);
        let date = start_pp - Duration::days(15);
        c.start_pay_period = Some(start_pp.clone());
        c.length_pay_period = 7;
        assert_eq!(
            date + Duration::days(1),
            c.next_start_pay_period(&date).unwrap()
        )
    }
}