1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
use crate::storage::{DataStore, MemoryDataStore};
use crate::time::Time;
use crate::utils::CaseInsensitiveStr;
use crate::world::npc::{NpcData, NpcRelations};
use crate::world::place::{Place, PlaceData, PlaceRelations};
use crate::world::thing::{Thing, ThingData, ThingRelations};
use crate::Uuid;
use futures::join;
use std::collections::VecDeque;
use std::fmt;

type Name = String;

const RECENT_MAX_LEN: usize = 100;
const UNDO_HISTORY_LEN: usize = 10;

pub struct Repository {
    data_store: Box<dyn DataStore>,
    data_store_enabled: bool,
    recent: VecDeque<Thing>,
    redo_change: Option<Change>,
    undo_history: VecDeque<Change>,
}

/// Represents a modification to be applied to the Repository. This is passed to
/// Repository::modify() to be applied. An object is used to represent the change because every
/// operation has an opposite; for instance, Unsave is the opposite of Save, and Edit is the
/// opposite of Edit. This opposite is inserted into the undo history and can be applied using
/// Repository::undo().
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Change {
    /// Create a new thing and store it in recent entries.
    ///
    /// Reverse: Delete
    Create {
        thing_data: ThingData,
        uuid: Option<Uuid>,
    },

    /// Create a new thing and store it in the journal.
    ///
    /// Reverse: Delete
    CreateAndSave {
        thing_data: ThingData,
        uuid: Option<Uuid>,
    },

    /// Delete a thing from recent or journal.
    ///
    /// Reverse: Create (recent) or CreateAndSave (journal)
    Delete { uuid: Uuid, name: Name },

    /// Edit fields on a Thing.
    ///
    /// Reverse: Edit (already in journal) or EditAndUnsave (in recent)
    Edit {
        name: Name,
        uuid: Option<Uuid>,
        diff: ThingData,
    },

    /// Edit a Thing and move it from journal to recent. The reverse of edit with autosave.
    ///
    /// Reverse: Edit
    EditAndUnsave {
        uuid: Uuid,
        name: Name,
        diff: ThingData,
    },

    /// Transfer a thing from recent to journal.
    ///
    /// Reverse: Unsave
    Save { name: Name, uuid: Option<Uuid> },

    /// Transfer a thing from journal to recent. Only triggerable as the reverse to Save.
    ///
    /// Reverse: Save
    Unsave { uuid: Uuid, name: Name },

    /// Set a value in the key-value store.
    ///
    /// Reverse: SetKeyValue
    SetKeyValue { key_value: KeyValue },
}

pub struct DisplayUndo<'a>(&'a Change);

pub struct DisplayRedo<'a>(&'a Change);

#[derive(Debug, Eq, PartialEq)]
pub enum Error {
    DataStoreFailed,
    MissingName,
    UuidAlreadyExists(Thing),
    NameAlreadyExists(Thing),
    NotFound,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum KeyValue {
    Time(Option<Time>),
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Record {
    pub status: RecordStatus,
    pub thing: Thing,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum RecordStatus {
    Unsaved,
    Saved,
    Deleted,
}

impl Repository {
    pub fn new(data_store: impl DataStore + 'static) -> Self {
        Self {
            data_store: Box::new(data_store),
            data_store_enabled: false,
            recent: VecDeque::default(),
            redo_change: None,
            undo_history: VecDeque::default(),
        }
    }

    /// The data store will not necessarily be available at construct, so we need to check if it's
    /// healthy or discard it and fall back on a memory data store instead.
    pub async fn init(&mut self) {
        if self.data_store.health_check().await.is_ok() {
            self.data_store_enabled = true;
        } else {
            self.data_store = Box::<MemoryDataStore>::default();
        }
    }

    /// Get the record associated with a given change, if available.
    pub async fn get_by_change(&self, change: &Change) -> Result<Record, Error> {
        let (name, uuid) = match change {
            Change::Create {
                uuid: Some(uuid), ..
            }
            | Change::CreateAndSave {
                uuid: Some(uuid), ..
            }
            | Change::EditAndUnsave { uuid, .. }
            | Change::Save {
                uuid: Some(uuid), ..
            }
            | Change::Unsave { uuid, .. }
            | Change::Delete { uuid, .. }
            | Change::Edit {
                uuid: Some(uuid), ..
            } => (None, Some(uuid)),
            Change::Create { thing_data, .. } | Change::CreateAndSave { thing_data, .. } => {
                (thing_data.name().value(), None)
            }
            Change::Save { name, .. } | Change::Edit { name, .. } => (Some(name), None),
            Change::SetKeyValue { .. } => (None, None),
        };

        if let Some(uuid) = uuid {
            self.get_by_uuid(uuid).await
        } else if let Some(name) = name {
            self.get_by_name(name).await
        } else {
            Err(Error::NotFound)
        }
    }

    /// Load child and grandchild relations associated with a Thing (eg. location).
    pub async fn load_relations(&self, thing: &Thing) -> Result<ThingRelations, Error> {
        let locations = {
            let parent_uuid = match &thing.data {
                ThingData::Npc(NpcData { location_uuid, .. }) => location_uuid,
                ThingData::Place(PlaceData { location_uuid, .. }) => location_uuid,
            };

            let parent = {
                let parent_result = if let Some(uuid) = parent_uuid.value() {
                    self.get_by_uuid(uuid).await.and_then(|record| {
                        Place::try_from(record.thing).map_err(|_| Error::NotFound)
                    })
                } else {
                    Err(Error::NotFound)
                };

                match parent_result {
                    Ok(parent) => Some(parent),
                    Err(Error::NotFound) => None,
                    Err(e) => return Err(e),
                }
            };

            if let Some(parent) = parent {
                let grandparent = {
                    let grandparent_result = if let Some(uuid) = parent.data.location_uuid.value() {
                        self.get_by_uuid(uuid).await.and_then(|record| {
                            Place::try_from(record.thing).map_err(|_| Error::NotFound)
                        })
                    } else {
                        Err(Error::NotFound)
                    };

                    match grandparent_result {
                        Ok(grandparent) => Some(grandparent),
                        Err(Error::NotFound) => None,
                        Err(e) => return Err(e),
                    }
                };

                Some((parent, grandparent))
            } else {
                None
            }
        };

        match thing.data {
            ThingData::Npc(..) => Ok(NpcRelations {
                location: locations,
            }
            .into()),
            ThingData::Place(..) => Ok(PlaceRelations {
                location: locations,
            }
            .into()),
        }
    }

    /// Get all saved and recent Things beginning with a given (case-insensitive) string, up to an
    /// optional limit.
    pub async fn get_by_name_start(
        &self,
        name: &str,
        limit: Option<usize>,
    ) -> Result<Vec<Record>, Error> {
        Ok(self
            .data_store
            .get_things_by_name_start(name, limit)
            .await
            .map_err(|_| Error::DataStoreFailed)?
            .into_iter()
            .map(|thing| Record {
                status: RecordStatus::Saved,
                thing,
            })
            .chain(
                self.recent()
                    .filter(|t| t.name().value().map_or(false, |s| s.starts_with_ci(name)))
                    .map(|thing| Record {
                        status: RecordStatus::Unsaved,
                        thing: thing.clone(),
                    }),
            )
            .take(limit.unwrap_or(usize::MAX))
            .collect())
    }

    /// Get an iterator over all recent Things.
    pub fn recent(&self) -> impl Iterator<Item = &Thing> {
        let (a, b) = self.recent.as_slices();
        a.iter().chain(b.iter())
    }

    /// Get all Things contained in the journal. This could get heavy, so should not be used
    /// lightly.
    pub async fn journal(&self) -> Result<Vec<Thing>, Error> {
        self.data_store
            .get_all_the_things()
            .await
            .map_err(|_| Error::DataStoreFailed)
    }

    /// Get the Thing from saved or recent with a given name. (There should be only one.)
    pub async fn get_by_name(&self, name: &str) -> Result<Record, Error> {
        let (recent_thing, saved_thing) = join!(
            async {
                self.recent()
                    .find(|t| t.name().value().map_or(false, |s| s.eq_ci(name)))
            },
            self.data_store.get_thing_by_name(name)
        );

        match (recent_thing, saved_thing) {
            (Some(thing), _) => Ok(Record {
                status: RecordStatus::Unsaved,
                thing: thing.clone(),
            }),
            (None, Ok(Some(thing))) => Ok(Record {
                status: RecordStatus::Saved,
                thing,
            }),
            (None, Ok(None)) => Err(Error::NotFound),
            (None, Err(())) => Err(Error::DataStoreFailed),
        }
    }

    /// Get the Thing from saved or recent with a given UUID. (There should be only one.)
    pub async fn get_by_uuid(&self, uuid: &Uuid) -> Result<Record, Error> {
        let (recent_thing, saved_thing) = join!(
            async { self.recent().find(|t| &t.uuid == uuid) },
            self.data_store.get_thing_by_uuid(uuid)
        );

        match (recent_thing, saved_thing) {
            (Some(thing), _) => Ok(Record {
                status: RecordStatus::Unsaved,
                thing: thing.clone(),
            }),
            (None, Ok(Some(thing))) => Ok(Record {
                status: RecordStatus::Saved,
                thing,
            }),
            (None, Ok(None)) => Err(Error::NotFound),
            (None, Err(())) => Err(Error::DataStoreFailed),
        }
    }

    /// Apply a given Change, returning the affected Thing (with modifications applied) on success,
    /// or a tuple of the Change and Error message on failure.
    pub async fn modify(&mut self, change: Change) -> Result<Option<Record>, (Change, Error)> {
        // If we're going to delete, we should load the record being deleted first because
        // otherwise it'll be gone!
        let mut option_record = if matches!(change, Change::Delete { .. }) {
            self.get_by_change(&change).await.ok().map(|mut record| {
                record.status = RecordStatus::Deleted;
                record
            })
        } else {
            None
        };

        let undo_change = self.modify_without_undo(change).await?;

        if option_record.is_none() {
            option_record = self.get_by_change(&undo_change).await.ok();
        }

        while self.undo_history.len() >= UNDO_HISTORY_LEN {
            self.undo_history.pop_front();
        }
        self.undo_history.push_back(undo_change);

        Ok(option_record)
    }

    /// Undo the most recent Change. Returns None if the undo history is empty; otherwise returns
    /// the Result of the modify() operation.
    pub async fn undo(&mut self) -> Option<Result<Option<Record>, Error>> {
        if let Some(change) = self.undo_history.pop_back() {
            match self.modify_without_undo(change).await {
                Ok(redo_change) => {
                    let record = self.get_by_change(&redo_change).await.ok();
                    self.redo_change = Some(redo_change);
                    Some(Ok(record))
                }
                Err((undo_change, e)) => {
                    self.undo_history.push_back(undo_change);
                    Some(Err(e))
                }
            }
        } else {
            None
        }
    }

    /// Get an iterator over the Changes currently queued up in the undo history, from newest to
    /// oldest.
    pub fn undo_history(&self) -> impl Iterator<Item = &Change> {
        self.undo_history.iter().rev()
    }

    /// Redo the most recently undid Change. Returns None if no such change exists; otherwise
    /// returns the result of the modify() operation. This differs from undo() in that only one
    /// Change is stored in history at a time.
    pub async fn redo(&mut self) -> Option<Result<Option<Record>, Error>> {
        if let Some(change) = self.redo_change.take() {
            match self.modify(change).await {
                Ok(option_record) => Some(Ok(option_record)),
                Err((redo_change, e)) => {
                    self.redo_change = Some(redo_change);
                    Some(Err(e))
                }
            }
        } else {
            None
        }
    }

    /// Get the Change currently queued up for redo(), if any.
    pub fn get_redo(&self) -> Option<&Change> {
        self.redo_change.as_ref()
    }

    /// Apply a Change to the Repository without adding the Change to the undo history. Returns
    /// the reverse operation on success (what would be otherwise inserted into the undo history),
    /// or a tuple of the failed Change and error message on failure.
    pub async fn modify_without_undo(&mut self, change: Change) -> Result<Change, (Change, Error)> {
        match change {
            Change::Create { thing_data, uuid } => {
                let name = thing_data.name().to_string();
                self.create_thing(thing_data, uuid)
                    .await
                    .map(|uuid| Change::Delete { uuid, name })
                    .map_err(|(thing_data, e)| (Change::Create { thing_data, uuid }, e))
            }
            Change::CreateAndSave { thing_data, uuid } => {
                let name = thing_data.name().to_string();
                self.create_and_save_thing(thing_data, uuid)
                    .await
                    .map(|thing| Change::Delete {
                        uuid: thing.uuid,
                        name,
                    })
                    .map_err(|(thing_data, e)| (Change::CreateAndSave { thing_data, uuid }, e))
            }
            Change::Delete { uuid, name } => self
                .delete_thing_by_uuid(&uuid)
                .await
                .map(|Record { thing, status }| {
                    if status == RecordStatus::Saved {
                        Change::CreateAndSave {
                            thing_data: thing.data,
                            uuid: Some(thing.uuid),
                        }
                    } else {
                        Change::Create {
                            thing_data: thing.data,
                            uuid: Some(thing.uuid),
                        }
                    }
                })
                .map_err(|(_, e)| (Change::Delete { uuid, name }, e)),
            Change::Edit {
                name,
                uuid: None,
                diff,
            } => match self.edit_thing_by_name(&name, diff).await {
                Ok((Record { thing, status }, name)) => {
                    if status == RecordStatus::Saved {
                        Ok(Change::Edit {
                            uuid: Some(thing.uuid),
                            name,
                            diff: thing.data,
                        })
                    } else {
                        Ok(Change::EditAndUnsave {
                            uuid: thing.uuid,
                            name,
                            diff: thing.data,
                        })
                    }
                }
                Err((option_record, diff, e)) => Err((
                    Change::Edit {
                        name: option_record
                            .map(|record| record.thing.name().value().map(String::from))
                            .unwrap_or(None)
                            .unwrap_or(name),
                        uuid: None,
                        diff,
                    },
                    e,
                )),
            },
            Change::Edit {
                name,
                uuid: Some(uuid),
                diff,
            } => match self.edit_thing_by_uuid(&uuid, diff).await {
                Ok((Record { thing, status }, name)) => {
                    let diff = thing.data;

                    if status == RecordStatus::Saved {
                        let uuid = Some(uuid);
                        Ok(Change::Edit { uuid, name, diff })
                    } else {
                        Ok(Change::EditAndUnsave { uuid, name, diff })
                    }
                }
                Err((option_record, diff, e)) => Err((
                    Change::Edit {
                        name: option_record
                            .map(|record| record.thing.name().value().map(String::from))
                            .unwrap_or(None)
                            .unwrap_or(name),
                        uuid: Some(uuid),
                        diff,
                    },
                    e,
                )),
            },
            Change::EditAndUnsave { uuid, name, diff } => {
                match self.edit_thing_by_uuid(&uuid, diff).await {
                    Ok((Record { thing, .. }, name)) => self
                        .unsave_thing_by_uuid(&uuid)
                        .await
                        .map(|name| Change::Edit {
                            name,
                            uuid: Some(uuid),
                            diff: thing.data,
                        })
                        .map_err(|(s, e)| {
                            (
                                Change::Unsave {
                                    uuid,
                                    name: s.unwrap_or(name),
                                },
                                e,
                            )
                        }),
                    Err((_, diff, e)) => Err((Change::EditAndUnsave { uuid, name, diff }, e)),
                }
            }
            Change::Save {
                name,
                uuid: Some(uuid),
            } => match self.save_thing_by_uuid(&uuid).await {
                Ok(thing) => Ok(Change::Unsave {
                    uuid,
                    name: thing.name().value().map(String::from).unwrap_or(name),
                }),
                Err(e) => Err((
                    Change::Save {
                        name,
                        uuid: Some(uuid),
                    },
                    e,
                )),
            },
            Change::Save { name, uuid: None } => match self.save_thing_by_name(&name).await {
                Ok(thing) => Ok(Change::Unsave {
                    uuid: thing.uuid,
                    name: thing.name().value().map(String::from).unwrap_or(name),
                }),
                Err(e) => Err((Change::Save { name, uuid: None }, e)),
            },
            Change::Unsave { uuid, name } => self
                .unsave_thing_by_uuid(&uuid)
                .await
                .map(|name| Change::Save {
                    name,
                    uuid: Some(uuid),
                })
                .map_err(|(_, e)| (Change::Unsave { uuid, name }, e)),
            Change::SetKeyValue { key_value } => self
                .set_key_value(&key_value)
                .await
                .map(|old_kv| Change::SetKeyValue { key_value: old_kv })
                .map_err(|e| (Change::SetKeyValue { key_value }, e)),
        }
    }

    /// Get a value from the key-value store.
    pub async fn get_key_value(&self, key: &KeyValue) -> Result<KeyValue, Error> {
        let value_str = self.data_store.get_value(key.key_raw()).await;

        match key {
            KeyValue::Time(_) => value_str
                .and_then(|o| o.map(|s| s.parse()).transpose())
                .map(KeyValue::Time),
        }
        .map_err(|_| Error::DataStoreFailed)
    }

    /// Is the data store currently enabled? Returns false if init() has not yet been called.
    pub fn data_store_enabled(&self) -> bool {
        self.data_store_enabled
    }

    /// Set a value in the key-value store.
    ///
    /// Publicly this is done using modify() with Change::SetKeyValue.
    async fn set_key_value(&mut self, key_value: &KeyValue) -> Result<KeyValue, Error> {
        let old_key_value = self.get_key_value(key_value).await?;

        match key_value.key_value_raw() {
            (key, Some(value)) => self.data_store.set_value(key, &value).await,
            (key, None) => self.data_store.delete_value(key).await,
        }
        .map(|_| old_key_value)
        .map_err(|_| Error::DataStoreFailed)
    }

    /// Add a Thing to the recent list.
    fn push_recent(&mut self, thing: Thing) {
        while self.recent.len() >= RECENT_MAX_LEN {
            self.recent.pop_front();
        }

        self.recent.push_back(thing);
    }

    /// Remove the latest Thing in the recent list, returning it if one is present.
    fn take_recent<F>(&mut self, f: F) -> Option<Thing>
    where
        F: Fn(&Thing) -> bool,
    {
        if let Some(index) =
            self.recent
                .iter()
                .enumerate()
                .find_map(|(i, t)| if f(t) { Some(i) } else { None })
        {
            self.recent.remove(index)
        } else {
            None
        }
    }

    /// Create a Thing, pushing it onto the recent list.
    ///
    /// Publicly this is invoked using modify() with Change::Create.
    async fn create_thing(
        &mut self,
        thing_data: ThingData,
        uuid: Option<Uuid>,
    ) -> Result<Uuid, (ThingData, Error)> {
        let thing = self.thing_data_into_thing(thing_data, uuid).await?;
        let uuid = thing.uuid;
        self.push_recent(thing);
        Ok(uuid)
    }

    /// Create a Thing and save it directly to the journal.
    ///
    /// Publicly this is invoked using modify() with Change::CreateAndSave.
    async fn create_and_save_thing(
        &mut self,
        thing_data: ThingData,
        uuid: Option<Uuid>,
    ) -> Result<Thing, (ThingData, Error)> {
        let thing = self.thing_data_into_thing(thing_data, uuid).await?;

        match self.save_thing(&thing).await {
            Ok(()) => Ok(thing),
            Err(e) => Err((thing.data, e)),
        }
    }

    /// Delete a Thing from recent or journal by its UUID.
    ///
    /// Publicly this is invoked using modify() with Change::Delete.
    async fn delete_thing_by_uuid(
        &mut self,
        uuid: &Uuid,
    ) -> Result<Record, (Option<Record>, Error)> {
        if let Some(thing) = self.take_recent(|t| &t.uuid == uuid) {
            Ok(Record {
                status: RecordStatus::Unsaved,
                thing,
            })
        } else {
            let record = self.get_by_uuid(uuid).await.map_err(|e| (None, e))?;

            if self.data_store.delete_thing_by_uuid(uuid).await.is_ok() {
                Ok(record)
            } else {
                Err((Some(record), Error::DataStoreFailed))
            }
        }
    }

    /// Transfer a Thing from recent to the journal, referenced by its name. Returns the Thing
    /// transferred, or an error on failure.
    ///
    /// Publicly this is invoked using modify() with Change::Save { uuid: None, .. }
    async fn save_thing_by_name(&mut self, name: &Name) -> Result<Thing, Error> {
        if let Some(thing) = self.take_recent(|t| t.name().value().map_or(false, |s| s.eq_ci(name)))
        {
            match self.save_thing(&thing).await {
                Ok(()) => Ok(thing),
                Err(e) => {
                    self.push_recent(thing);
                    Err(e)
                }
            }
        } else {
            Err(Error::NotFound)
        }
    }

    /// Transfer a Thing from recent to the journal, referenced by its UUID. Returns the Thing
    /// transferred, or an error on failure.
    ///
    /// Publicly this is invoked using modify() with Change::Save { uuid: Some(_), .. }
    async fn save_thing_by_uuid(&mut self, uuid: &Uuid) -> Result<Thing, Error> {
        if let Some(thing) = self.take_recent(|t| &t.uuid == uuid) {
            match self.save_thing(&thing).await {
                Ok(()) => Ok(thing),
                Err(e) => {
                    self.push_recent(thing);
                    Err(e)
                }
            }
        } else {
            Err(Error::NotFound)
        }
    }

    /// Write a Thing to the data store.
    async fn save_thing(&mut self, thing: &Thing) -> Result<(), Error> {
        match self.data_store.save_thing(thing).await {
            Ok(()) => Ok(()),
            Err(()) => Err(Error::DataStoreFailed),
        }
    }

    /// Remove a Thing from the data store and add it to the recent list instead. Returns the name
    /// of the Thing transferred on success, or a tuple of the optional name and an error on
    /// failure. This is asymmetric with save_thing_by_* because writing to the recent list takes
    /// ownership while writing to the data store accepts a reference, so returning a Thing here
    /// would require an unnecessary clone() call when all we really want is the name of the Thing
    /// we just unsaved.
    ///
    /// Publicly this is invoked using modify() with Change::Unsave.
    async fn unsave_thing_by_uuid(&mut self, uuid: &Uuid) -> Result<Name, (Option<Name>, Error)> {
        let thing = match self.data_store.get_thing_by_uuid(uuid).await {
            Ok(Some(thing)) => Ok(thing),
            Ok(None) => Err((None, Error::NotFound)),
            Err(()) => Err((None, Error::DataStoreFailed)),
        }?;

        let name = thing.name().to_string();

        match self.data_store.delete_thing_by_uuid(uuid).await {
            Ok(()) => {
                self.push_recent(thing);
                Ok(name)
            }
            Err(()) => Err((Some(name), Error::DataStoreFailed)),
        }
    }

    /// Apply a diff to a Thing matched by name. See edit_thing() for details.
    ///
    /// Publicly this is invoked using modify() with Change::Edit { uuid: None, .. }.
    async fn edit_thing_by_name(
        &mut self,
        name: &Name,
        diff: ThingData,
    ) -> Result<(Record, Name), (Option<Record>, ThingData, Error)> {
        match self.get_by_name(name).await {
            Ok(record) => self
                .edit_thing(record, diff)
                .await
                .map_err(|(record, data, e)| (Some(record), data, e)),
            Err(e) => Err((None, diff, e)),
        }
    }

    /// Apply a diff to a Thing matched by UUID. See edit_thing() for details.
    ///
    /// Publicly this is invoked using modify() with Change::Edit { uuid: Some(_), .. }.
    async fn edit_thing_by_uuid(
        &mut self,
        uuid: &Uuid,
        diff: ThingData,
    ) -> Result<(Record, Name), (Option<Record>, ThingData, Error)> {
        match self.get_by_uuid(uuid).await {
            Ok(record) => self
                .edit_thing(record, diff)
                .await
                .map_err(|(record, data, e)| (Some(record), data, e)),
            Err(e) => Err((None, diff, e)),
        }
    }

    /// Apply a diff to a given Record. Returns a tuple consisting of a Record containing *the
    /// modified fields* and the matched Thing's actual name on success, or a tuple consisting of
    /// an optional Record of the matched Thing, the attempted diff, and an error message on
    /// failure. Note that the successful response includes only the old values of any modified
    /// fields, so re-applying the diff will revert the Thing back to its original state.
    ///
    /// Supports the edit_thing_by_* functions.
    async fn edit_thing(
        &mut self,
        mut record: Record,
        mut diff: ThingData,
    ) -> Result<(Record, Name), (Record, ThingData, Error)> {
        if record.thing.try_apply_diff(&mut diff).is_err() {
            // This fails when the thing types don't match, eg. applying an Npc diff to a
            // Place.
            return Err((record, diff, Error::NotFound));
        }

        let name = record.thing.name().to_string();
        let diff_thing = Thing {
            uuid: record.thing.uuid,
            data: diff,
        };

        if record.is_saved() {
            match self.data_store.edit_thing(&record.thing).await {
                Ok(()) => Ok((
                    Record {
                        status: RecordStatus::Saved,
                        thing: diff_thing,
                    },
                    name,
                )),
                Err(()) => Err((record, diff_thing.data, Error::DataStoreFailed)),
            }
        } else {
            let uuid = record.thing.uuid;
            self.take_recent(|t| t.uuid == uuid);

            if let Ok(()) = self.save_thing(&record.thing).await {
                Ok((
                    Record {
                        status: RecordStatus::Unsaved,
                        thing: diff_thing,
                    },
                    name,
                ))
            } else {
                // Fail forward when implicit save was unsuccessful so that we can at least edit
                // records in memory when the data store is unavailable.
                self.push_recent(record.thing);
                Ok((
                    Record {
                        status: RecordStatus::Saved,
                        thing: diff_thing,
                    },
                    name,
                ))
            }
        }
    }

    /// Creates a new Thing from its data, generating a UUID if necessary and checking for
    /// name/UUID conflicts.
    async fn thing_data_into_thing(
        &self,
        thing_data: ThingData,
        uuid: Option<Uuid>,
    ) -> Result<Thing, (ThingData, Error)> {
        let uuid = uuid.unwrap_or_else(Uuid::new_v4);

        if let Ok(record) = self.get_by_uuid(&uuid).await {
            Err((thing_data, Error::UuidAlreadyExists(record.thing)))
        } else if let Some(name) = thing_data.name().value() {
            if let Ok(record) = self.get_by_name(name).await {
                Err((thing_data, Error::NameAlreadyExists(record.thing)))
            } else {
                Ok(Thing {
                    uuid,
                    data: thing_data,
                })
            }
        } else {
            Err((thing_data, Error::MissingName))
        }
    }
}

impl KeyValue {
    pub const fn key_raw(&self) -> &'static str {
        match self {
            Self::Time(_) => "time",
        }
    }

    pub fn key_value_raw(&self) -> (&'static str, Option<String>) {
        (
            self.key_raw(),
            match self {
                Self::Time(time) => time.as_ref().map(|t| t.display_short().to_string()),
            },
        )
    }

    pub const fn time(self) -> Option<Time> {
        #[expect(irrefutable_let_patterns)]
        if let Self::Time(time) = self {
            time
        } else {
            None
        }
    }
}

impl Change {
    /// Describe how applying this change from the undo queue will affect the application state
    /// ("undo change xyz").
    pub fn display_undo(&self) -> DisplayUndo {
        DisplayUndo(self)
    }

    /// Describe how applyifrom the redo queue will affect the application state ("redo change
    /// xyz").
    pub fn display_redo(&self) -> DisplayRedo {
        DisplayRedo(self)
    }
}

impl Record {
    pub fn is_saved(&self) -> bool {
        self.status == RecordStatus::Saved
    }

    pub fn is_unsaved(&self) -> bool {
        self.status == RecordStatus::Unsaved
    }

    pub fn is_deleted(&self) -> bool {
        self.status == RecordStatus::Deleted
    }
}

impl<'a> fmt::Display for DisplayUndo<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        let change = self.0;

        // Note: these descriptions are _backward_ since they describe the reverse, ie. the action
        // that this Change will undo. Eg. Change::Create => "undo deleting x"
        match change {
            Change::Create { thing_data, .. } | Change::CreateAndSave { thing_data, .. } => {
                write!(f, "deleting {}", thing_data.name())
            }
            Change::Delete { name, .. } => write!(f, "creating {}", name),
            Change::Save { name, .. } => write!(f, "removing {} from journal", name),
            Change::Unsave { name, .. } => write!(f, "saving {} to journal", name),

            // These changes are symmetric, so we can provide the same output in both cases.
            Change::Edit { .. } | Change::EditAndUnsave { .. } | Change::SetKeyValue { .. } => {
                write!(f, "{}", DisplayRedo(change))
            }
        }
    }
}

impl<'a> fmt::Display for DisplayRedo<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        let change = self.0;

        match change {
            Change::Create { thing_data, .. } | Change::CreateAndSave { thing_data, .. } => {
                write!(f, "creating {}", thing_data.name())
            }
            Change::Delete { name, .. } => write!(f, "deleting {}", name),
            Change::Edit { name, .. } | Change::EditAndUnsave { name, .. } => {
                write!(f, "editing {}", name)
            }
            Change::Save { name, .. } => write!(f, "saving {} to journal", name),
            Change::Unsave { name, .. } => write!(f, "removing {} from journal", name),
            Change::SetKeyValue { key_value } => match key_value {
                KeyValue::Time(_) => write!(f, "changing the time"),
            },
        }
    }
}

impl fmt::Debug for Repository {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "Repository {{ data_store_enabled: {:?}, recent: {:?} }}",
            self.data_store_enabled, self.recent,
        )
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::storage::data_store::{MemoryDataStore, NullDataStore};
    use crate::world::npc::Npc;
    use crate::world::place::Place;
    use async_trait::async_trait;
    use std::cell::RefCell;
    use std::rc::Rc;
    use tokio_test::block_on;
    use uuid::Uuid;

    const OLYMPUS_UUID: Uuid = Uuid::from_u128(1);
    const THESSALY_UUID: Uuid = Uuid::from_u128(2);
    const GREECE_UUID: Uuid = Uuid::from_u128(3);
    const STYX_UUID: Uuid = Uuid::from_u128(4);
    const ODYSSEUS_UUID: Uuid = Uuid::from_u128(5);

    macro_rules! assert_change_success {
        ($change: expr, $is_changed:expr, $redo_message:expr, $undo_message:expr) => {
            let change: Change = $change;
            let is_changed: &dyn Fn(&Repository, &dyn DataStore) -> bool = &$is_changed;
            let undo_message: &str = $undo_message;
            let redo_message: &str = $redo_message;

            let (mut repo, data_store) = repo_data_store();
            assert_eq!(redo_message, change.display_redo().to_string(), "change.display_redo()");

            let (original_recent, original_data_store) = (repo.recent.clone(), data_store.snapshot());

            let (modified_recent, modified_data_store) = {
                // repo.modify()
                block_on(repo.modify(change)).unwrap();
                assert!(
                    is_changed(&repo, &data_store),
                    "`is_changed()` should return true after `repo.modify()`

repo.recent = {:?}

data_store.snapshot() = {:?}",
                    repo.recent,
                    data_store.snapshot(),
                );
                assert!(
                    original_recent != repo.recent || original_data_store != data_store.snapshot(),
                    "`repo.recent` AND/OR `data_store` should have changed after `repo.modify()`

repo.recent = {:?}

data_store.snapshot() = {:?}",
                    repo.recent,
                    data_store.snapshot(),
                );

                assert_eq!(
                    undo_message,
                    repo.undo_history()
                        .next()
                        .unwrap()
                        .display_undo()
                        .to_string(),
                    "`undo_history().display_undo()`",
                );

                (repo.recent.clone(), data_store.snapshot())
            };

            {
                let undo_change = repo.undo_history().next().cloned();

                // repo.undo()
                block_on(repo.undo()).unwrap().unwrap();
                assert!(
                    !is_changed(&repo, &data_store),
                    "is_changed() should return false after repo.undo()

change = {:?}

repo.recent = {:?}

data_store.snapshot() = {:?}",
                    undo_change,
                    repo.recent,
                    data_store.snapshot(),
                );
                assert_eq!(
                    original_recent,
                    repo.recent,
                    "`repo.recent` should reset after `repo.undo()`\n\nchange = {:?}",
                    undo_change,
                );
                assert_eq!(
                    original_data_store,
                    data_store.snapshot(),
                    "`data_store` should reset after `repo.undo()`\n\nchange = {:?}",
                    undo_change,
                );
            }

            {
                // repo.redo()
                block_on(repo.redo());
                assert!(
                    is_changed(&repo, &data_store),
                    "is_changed() should return true after repo.redo()

repo.recent = {:?}

data_store.snapshot() = {:?}",
                    repo.recent,
                    data_store.snapshot(),
                );
                assert_eq!(
                    modified_recent,
                    repo.recent,
                    "`repo.recent` should return to its changed state after `repo.redo()`",
                );
                assert_eq!(
                    modified_data_store,
                    data_store.snapshot(),
                    "`data_store` should return to its changed state after `repo.redo()`",
                );
            }
        }
    }

    macro_rules! assert_change_error {
        ($repo_data_store: expr, $change:expr, $error:expr) => {
            let (mut repo, data_store): (Repository, MemoryDataStore) = $repo_data_store;
            let change: Change = $change;
            let error: Error = $error;

            let (original_recent, original_data_store) =
                (repo.recent.clone(), data_store.snapshot());

            let result = block_on(repo.modify(change.clone()));

            assert_eq!(Err((change, error)), result);
            assert_eq!(original_recent, repo.recent);
            assert_eq!(original_data_store, data_store.snapshot());
        };
    }

    macro_rules! assert_change_data_store_failed {
        ($change:expr) => {
            let change: Change = $change;

            let mut repo = null_repo();
            let original_recent = repo.recent.clone();

            let result = block_on(repo.modify(change.clone()));

            assert_eq!(Err((change, Error::DataStoreFailed)), result);
            assert_eq!(original_recent, repo.recent);
        };
    }

    #[test]
    fn recent_test() {
        let mut repository = empty_repo();

        (0..RECENT_MAX_LEN).for_each(|i| {
            repository.push_recent(thing(
                Uuid::from_u128(i.try_into().unwrap()),
                NpcData {
                    name: format!("Thing {}", i).into(),
                    ..Default::default()
                },
            ));
            assert_eq!(i + 1, repository.recent.len());
        });

        assert_eq!(
            Some(&"Thing 0".to_string()),
            repository
                .recent()
                .next()
                .and_then(|thing| thing.name().value()),
        );

        repository.push_recent(thing(
            Uuid::from_u128(u128::MAX),
            NpcData {
                name: "The Cat in the Hat".into(),
                ..Default::default()
            },
        ));
        assert_eq!(RECENT_MAX_LEN, repository.recent.len());

        assert_eq!(
            Some(&"Thing 1".to_string()),
            repository
                .recent()
                .next()
                .and_then(|thing| thing.name().value()),
        );

        assert_eq!(
            Some(&"The Cat in the Hat".to_string()),
            repository
                .recent()
                .last()
                .and_then(|thing| thing.name().value()),
        );
    }

    #[test]
    fn journal_recent_test() {
        let repo = repo();
        assert_eq!(4, block_on(repo.journal()).unwrap().len());
        assert_eq!(1, repo.recent().count());
    }

    #[test]
    fn get_by_name_test_from_recent() {
        let result = block_on(repo().get_by_name("ODYSSEUS")).unwrap();

        assert_eq!(RecordStatus::Unsaved, result.status);
        assert_eq!("Odysseus", result.thing.name().to_string());
    }

    #[test]
    fn get_by_name_test_from_journal() {
        let result = block_on(repo().get_by_name("OLYMPUS")).unwrap();

        assert_eq!(RecordStatus::Saved, result.status);
        assert_eq!("Olympus", result.thing.name().to_string());
    }

    #[test]
    fn get_by_name_test_not_found() {
        assert_eq!(Err(Error::NotFound), block_on(repo().get_by_name("NOBODY")));
    }

    #[test]
    fn get_by_uuid_test_from_recent() {
        let result = block_on(repo().get_by_uuid(&ODYSSEUS_UUID)).unwrap();

        assert_eq!(RecordStatus::Unsaved, result.status);
        assert_eq!("Odysseus", result.thing.name().to_string());
    }

    #[test]
    fn get_by_uuid_test_from_journal() {
        let result = block_on(repo().get_by_uuid(&OLYMPUS_UUID)).unwrap();

        assert_eq!(RecordStatus::Saved, result.status);
        assert_eq!("Olympus", result.thing.name().to_string());
    }

    #[test]
    fn change_test_delete_from_journal_success() {
        assert_change_success!(
            Change::Delete {
                uuid: OLYMPUS_UUID,
                name: "blah".to_string(),
            },
            |repo, _| block_on(repo.get_by_name("Olympus")) == Err(Error::NotFound),
            "deleting blah",
            "deleting Olympus"
        );
    }

    #[test]
    fn change_test_delete_from_recent_success() {
        assert_change_success!(
            Change::Delete {
                uuid: ODYSSEUS_UUID,
                name: "blah".to_string(),
            },
            |repo, _| block_on(repo.get_by_name("Odysseus")) == Err(Error::NotFound),
            "deleting blah",
            "deleting Odysseus"
        );
    }

    #[test]
    fn change_test_delete_not_found() {
        assert_change_error!(
            repo_data_store(),
            Change::Delete {
                uuid: Uuid::nil(),
                name: "Nobody".to_string(),
            },
            Error::NotFound
        );
    }

    #[test]
    fn change_test_delete_data_store_failed() {
        assert_change_data_store_failed!(Change::Delete {
            uuid: OLYMPUS_UUID,
            name: "Olympus".to_string(),
        });
    }

    #[test]
    fn change_test_edit_by_name_from_recent_success() {
        assert_change_success!(
            Change::Edit {
                name: "ODYSSEUS".into(),
                uuid: None,
                diff: NpcData {
                    name: "Nobody".into(),
                    ..Default::default()
                }
                .into(),
            },
            |_, ds| {
                block_on(ds.get_thing_by_uuid(&ODYSSEUS_UUID))
                    .map(|opt_t| opt_t.map(|t| t.name().to_string()))
                    == Ok(Some("Nobody".to_string()))
            },
            "editing ODYSSEUS",
            "editing Nobody"
        );
    }

    #[test]
    fn change_test_edit_by_name_from_recent_wrong_type() {
        assert_change_error!(
            repo_data_store(),
            Change::Edit {
                name: "Odysseus".into(),
                uuid: None,
                diff: PlaceData::default().into(),
            },
            Error::NotFound
        );
    }

    #[test]
    fn change_test_edit_by_name_from_recent_data_store_failed() {
        let mut repo = repo();
        repo.data_store = Box::new(NullDataStore);
        let change = Change::Edit {
            name: "Odysseus".into(),
            uuid: None,
            diff: NpcData {
                name: "Nobody".into(),
                ..Default::default()
            }
            .into(),
        };

        {
            let result = block_on(repo.modify(change));

            assert_eq!(
                Ok(Some("Nobody".to_string())),
                result.map(|opt_r| opt_r.map(|r| r.thing.name().to_string())),
            );
            assert!(repo.recent().any(|t| t.name().to_string() == "Nobody"));
        }

        {
            let undo_change = repo.undo_history().next().cloned();
            let undo_result = block_on(repo.undo());

            assert_eq!(
                Ok(Some("Odysseus".to_string())),
                undo_result
                    .unwrap()
                    .map(|opt_r| opt_r.map(|r| r.thing.name().to_string())),
                "{:?}",
                undo_change,
            );
            assert!(repo.recent().any(|t| t.name().to_string() == "Odysseus"));
        }

        {
            let redo_result = block_on(repo.redo());

            assert_eq!(
                Ok(Some("Nobody".to_string())),
                redo_result
                    .unwrap()
                    .map(|opt_r| opt_r.map(|r| r.thing.name().to_string())),
            );
            assert!(repo.recent().any(|t| t.name().to_string() == "Nobody"));
        }
    }

    #[test]
    fn change_test_edit_by_name_from_journal_success() {
        assert_change_success!(
            Change::Edit {
                name: "OLYMPUS".into(),
                uuid: None,
                diff: PlaceData {
                    name: "Hades".into(),
                    description: "This really is hell!".into(),
                    ..Default::default()
                }
                .into(),
            },
            |_, ds| {
                block_on(ds.get_thing_by_uuid(&OLYMPUS_UUID))
                    .map(|opt_t| opt_t.map(|t| t.name().to_string()))
                    == Ok(Some("Hades".to_string()))
            },
            "editing OLYMPUS",
            "editing Hades"
        );
    }

    #[test]
    fn change_test_edit_by_name_from_journal_wrong_type() {
        assert_change_error!(
            repo_data_store(),
            Change::Edit {
                name: "Olympus".into(),
                uuid: None,
                diff: NpcData::default().into(),
            },
            Error::NotFound
        );
    }

    #[test]
    fn change_test_edit_by_name_from_journal_data_store_failed() {
        assert_change_data_store_failed!(Change::Edit {
            name: "Olympus".into(),
            uuid: None,
            diff: PlaceData {
                name: "Hades".into(),
                ..Default::default()
            }
            .into(),
        });
    }

    #[test]
    fn change_test_edit_by_name_not_found() {
        assert_change_error!(
            repo_data_store(),
            Change::Edit {
                name: "Nobody".into(),
                uuid: None,
                diff: NpcData::default().into(),
            },
            Error::NotFound
        );
    }

    #[test]
    fn change_test_edit_by_uuid_from_recent_success() {
        assert_change_success!(
            Change::Edit {
                name: "blah".into(),
                uuid: Some(ODYSSEUS_UUID),
                diff: NpcData {
                    name: "Nobody".into(),
                    ..Default::default()
                }
                .into(),
            },
            |repo, ds| {
                block_on(ds.get_thing_by_uuid(&ODYSSEUS_UUID))
                    .map(|opt_t| opt_t.map(|t| t.name().to_string()))
                    == Ok(Some("Nobody".to_string()))
                    && !repo.recent().any(|t| t.uuid == ODYSSEUS_UUID)
            },
            "editing blah",
            "editing Nobody"
        );
    }

    #[test]
    fn change_test_edit_by_uuid_from_journal_success() {
        assert_change_success!(
            Change::Edit {
                name: "blah".into(),
                uuid: Some(OLYMPUS_UUID),
                diff: PlaceData {
                    name: "Hades".into(),
                    description: "This really is hell!".into(),
                    ..Default::default()
                }
                .into(),
            },
            |_, ds| {
                block_on(ds.get_thing_by_uuid(&OLYMPUS_UUID))
                    .map(|opt_t| opt_t.map(|t| t.name().to_string()))
                    == Ok(Some("Hades".to_string()))
            },
            "editing blah",
            "editing Hades"
        );
    }

    #[test]
    fn change_test_edit_by_uuid_wrong_type() {
        assert_change_error!(
            repo_data_store(),
            Change::Edit {
                name: "Olympus".into(),
                uuid: Some(OLYMPUS_UUID),
                diff: NpcData::default().into(),
            },
            Error::NotFound
        );
    }

    #[test]
    fn change_test_edit_by_uuid_not_found() {
        assert_change_error!(
            repo_data_store(),
            Change::Edit {
                name: "Nobody".into(),
                uuid: Some(Uuid::nil()),
                diff: NpcData::default().into(),
            },
            Error::NotFound
        );
    }

    #[test]
    fn change_test_edit_by_uuid_from_journal_data_store_failed() {
        assert_change_data_store_failed!(Change::Edit {
            name: "Olympus".into(),
            uuid: Some(OLYMPUS_UUID),
            diff: PlaceData {
                name: "Hades".into(),
                description: "This really is hell!".into(),
                ..Default::default()
            }
            .into(),
        });
    }

    #[test]
    fn change_test_edit_and_unsave_success() {
        assert_change_success!(
            Change::EditAndUnsave {
                uuid: OLYMPUS_UUID,
                name: "blah".into(),
                diff: PlaceData {
                    name: "Hades".into(),
                    description: "This really is hell!".into(),
                    ..Default::default()
                }
                .into(),
            },
            |repo, ds| {
                repo.recent().any(|t| t.name().to_string() == "Hades")
                    && block_on(ds.get_thing_by_uuid(&OLYMPUS_UUID)) == Ok(None)
            },
            "editing blah",
            "editing Hades"
        );
    }

    #[test]
    fn change_test_edit_and_unsave_not_found() {
        assert_change_error!(
            repo_data_store(),
            Change::EditAndUnsave {
                name: "Nobody".into(),
                uuid: Uuid::nil(),
                diff: NpcData::default().into(),
            },
            Error::NotFound
        );
    }

    #[test]
    fn change_test_edit_and_unsave_data_store_failed() {
        let mut repo = Repository::new(TimeBombDataStore::new(7));
        populate_repo(&mut repo);

        let change = Change::EditAndUnsave {
            name: "Olympus".into(),
            uuid: OLYMPUS_UUID,
            diff: PlaceData {
                name: "Hades".into(),
                description: "This really is hell!".into(),
                ..Default::default()
            }
            .into(),
        };

        assert_eq!(
            Err((
                Change::Unsave {
                    name: "Hades".into(),
                    uuid: OLYMPUS_UUID,
                },
                Error::DataStoreFailed,
            )),
            block_on(repo.modify(change)),
        );
    }

    #[test]
    fn change_test_create_success() {
        assert_change_success!(
            Change::Create {
                thing_data: NpcData {
                    name: "Penelope".into(),
                    ..Default::default()
                }
                .into(),
                uuid: None,
            },
            |repo, _| repo.recent().any(|t| t.name().to_string() == "Penelope"),
            "creating Penelope",
            "creating Penelope"
        );
    }

    #[test]
    fn change_test_create_name_already_exists_in_journal() {
        let (repo, data_store) = repo_data_store();
        let existing_thing = block_on(data_store.get_thing_by_uuid(&OLYMPUS_UUID))
            .unwrap()
            .unwrap()
            .clone();

        assert_change_error!(
            (repo, data_store),
            Change::Create {
                thing_data: NpcData {
                    name: "OLYMPUS".into(),
                    ..Default::default()
                }
                .into(),
                uuid: None,
            },
            Error::NameAlreadyExists(existing_thing)
        );
    }

    #[test]
    fn change_test_create_name_already_exists_in_recent() {
        let (repo, data_store) = repo_data_store();
        let existing_thing = repo
            .recent()
            .find(|t| t.uuid == ODYSSEUS_UUID)
            .unwrap()
            .clone();

        assert_change_error!(
            (repo, data_store),
            Change::Create {
                thing_data: NpcData {
                    name: "ODYSSEUS".into(),
                    ..Default::default()
                }
                .into(),
                uuid: None,
            },
            Error::NameAlreadyExists(existing_thing)
        );
    }

    #[test]
    fn change_test_save_by_name_success() {
        assert_change_success!(
            Change::Save {
                name: "ODYSSEUS".to_string(),
                uuid: None,
            },
            |repo, ds| {
                block_on(ds.get_thing_by_uuid(&ODYSSEUS_UUID))
                    .map(|opt_t| opt_t.map(|t| t.name().to_string()))
                    == Ok(Some("Odysseus".to_string()))
                    && !repo.recent().any(|t| t.uuid == ODYSSEUS_UUID)
            },
            "saving ODYSSEUS to journal",
            "saving Odysseus to journal"
        );
    }

    #[test]
    fn change_test_save_data_store_failed() {
        let mut repo = null_repo();

        block_on(
            repo.modify(Change::Create {
                thing_data: PlaceData {
                    name: "Odysseus".into(),
                    ..Default::default()
                }
                .into(),
                uuid: None,
            }),
        )
        .unwrap();

        let original_recent = repo.recent.clone();

        let change = Change::Save {
            name: "ODYSSEUS".to_string(),
            uuid: None,
        };
        assert_eq!(
            block_on(repo.modify(change.clone())),
            Err((change, Error::DataStoreFailed)),
        );

        assert_eq!(original_recent, repo.recent);
    }

    #[test]
    fn change_test_save_already_saved() {
        assert_change_error!(
            repo_data_store(),
            Change::Save {
                name: "OLYMPUS".to_string(),
                uuid: None,
            },
            Error::NotFound
        );
    }

    #[test]
    fn change_test_save_not_found() {
        assert_change_error!(
            repo_data_store(),
            Change::Save {
                name: "NOBODY".to_string(),
                uuid: None,
            },
            Error::NotFound
        );
    }

    #[test]
    fn change_test_unsave_success() {
        assert_change_success!(
            Change::Unsave {
                uuid: OLYMPUS_UUID,
                name: "blah".to_string(),
            },
            |repo, ds| {
                block_on(ds.get_thing_by_uuid(&OLYMPUS_UUID)) == Ok(None)
                    && repo.recent().any(|t| t.uuid == OLYMPUS_UUID)
            },
            "removing blah from journal",
            "removing Olympus from journal"
        );
    }

    #[test]
    fn change_test_create_and_save_success() {
        assert_change_success!(
            Change::CreateAndSave {
                thing_data: NpcData {
                    name: "Penelope".into(),
                    ..Default::default()
                }
                .into(),
                uuid: None,
            },
            |_, ds| block_on(ds.get_thing_by_name("Penelope"))
                .unwrap()
                .is_some(),
            "creating Penelope",
            "creating Penelope"
        );
    }

    #[test]
    fn change_test_create_and_save_name_already_exists_in_journal() {
        let (repo, data_store) = repo_data_store();
        let existing_thing = block_on(data_store.get_thing_by_uuid(&OLYMPUS_UUID))
            .unwrap()
            .unwrap()
            .clone();

        assert_change_error!(
            (repo, data_store),
            Change::CreateAndSave {
                thing_data: NpcData {
                    name: "OLYMPUS".into(),
                    ..Default::default()
                }
                .into(),
                uuid: None,
            },
            Error::NameAlreadyExists(existing_thing)
        );
    }

    #[test]
    fn change_test_create_and_save_name_already_exists_in_recent() {
        let (repo, data_store) = repo_data_store();
        let existing_thing = repo
            .recent()
            .find(|t| t.uuid == ODYSSEUS_UUID)
            .unwrap()
            .clone();

        assert_change_error!(
            (repo, data_store),
            Change::CreateAndSave {
                thing_data: NpcData {
                    name: "ODYSSEUS".into(),
                    ..Default::default()
                }
                .into(),
                uuid: None,
            },
            Error::NameAlreadyExists(existing_thing)
        );
    }

    #[test]
    fn change_test_create_and_save_data_store_failed() {
        let mut repo = null_repo();

        let change = Change::CreateAndSave {
            thing_data: NpcData {
                name: "Odysseus".into(),
                ..Default::default()
            }
            .into(),
            uuid: None,
        };

        assert_eq!(
            block_on(repo.modify(change.clone())),
            Err((change, Error::DataStoreFailed)),
        );
    }

    #[test]
    fn change_test_set_key_value_success() {
        let mut repo = repo();

        let one = Time::try_new(1, 0, 0, 0).unwrap();
        let two = Time::try_new(2, 0, 0, 0).unwrap();

        assert_eq!(
            Ok(KeyValue::Time(None)),
            block_on(repo.get_key_value(&KeyValue::Time(None)))
        );

        assert_eq!(
            Ok(None),
            block_on(repo.modify(Change::SetKeyValue {
                key_value: KeyValue::Time(Some(one.clone())),
            })),
        );

        {
            let undo_result = repo.undo_history().next().unwrap();

            assert_eq!(
                &Change::SetKeyValue {
                    key_value: KeyValue::Time(None),
                },
                undo_result,
            );
            assert_eq!("changing the time", undo_result.display_undo().to_string());
            assert_eq!("changing the time", undo_result.display_redo().to_string());
        }

        block_on(repo.modify(Change::SetKeyValue {
            key_value: KeyValue::Time(Some(two.clone())),
        }))
        .unwrap();

        block_on(repo.modify(Change::SetKeyValue {
            key_value: KeyValue::Time(None),
        }))
        .unwrap();

        assert_eq!(
            Ok(KeyValue::Time(None)),
            block_on(repo.get_key_value(&KeyValue::Time(None)))
        );

        assert_eq!(Some(Ok(None)), block_on(repo.undo()));

        assert_eq!(
            Ok(KeyValue::Time(Some(two))),
            block_on(repo.get_key_value(&KeyValue::Time(None)))
        );

        block_on(repo.undo());

        assert_eq!(
            Ok(KeyValue::Time(Some(one))),
            block_on(repo.get_key_value(&KeyValue::Time(None)))
        );

        block_on(repo.undo());

        assert_eq!(
            Ok(KeyValue::Time(None)),
            block_on(repo.get_key_value(&KeyValue::Time(None)))
        );
    }

    #[test]
    fn change_test_set_key_value_data_store_failed() {
        let change = Change::SetKeyValue {
            key_value: KeyValue::Time(Some(Time::default())),
        };

        assert_eq!(
            block_on(null_repo().modify(change.clone())),
            Err((change, Error::DataStoreFailed)),
        );
    }

    #[test]
    fn load_relations_test_with_parent_success() {
        let repo = repo();
        let odysseus = block_on(repo.get_by_name("Odysseus")).unwrap().thing;

        match block_on(repo.load_relations(&odysseus)) {
            Ok(ThingRelations::Npc(NpcRelations {
                location: Some((parent, None)),
            })) => {
                assert_eq!("River Styx", parent.data.name.value().unwrap());
            }
            r => panic!("{:?}", r),
        }
    }

    #[test]
    fn load_relations_test_with_grandparent_success() {
        let repo = repo();
        let olympus = block_on(repo.get_by_uuid(&OLYMPUS_UUID)).unwrap().thing;

        match block_on(repo.load_relations(&olympus)) {
            Ok(ThingRelations::Place(PlaceRelations {
                location: Some((parent, Some(grandparent))),
            })) => {
                assert_eq!("Thessaly", parent.data.name.value().unwrap());
                assert_eq!("Greece", grandparent.data.name.value().unwrap());
            }
            r => panic!("{:?}", r),
        }
    }

    #[test]
    fn debug_test() {
        assert_eq!(
            "Repository { data_store_enabled: false, recent: [] }",
            format!("{:?}", empty_repo()),
        );
    }

    #[test]
    fn data_store_enabled_test_success() {
        let mut repo = repo();
        block_on(repo.init());
        assert!(repo.data_store_enabled());
    }

    #[test]
    fn data_store_enabled_test_failure() {
        let mut repo = null_repo();
        block_on(repo.init());
        assert!(!repo.data_store_enabled());
    }

    fn thing(uuid: Uuid, data: impl Into<ThingData>) -> Thing {
        Thing {
            uuid,
            data: data.into(),
        }
    }

    fn repo() -> Repository {
        repo_data_store().0
    }

    fn repo_data_store() -> (Repository, MemoryDataStore) {
        let data_store = MemoryDataStore::default();
        let mut repo = Repository::new(data_store.clone());
        populate_repo(&mut repo);
        (repo, data_store)
    }

    fn empty_repo() -> Repository {
        Repository::new(MemoryDataStore::default())
    }

    fn null_repo() -> Repository {
        Repository::new(NullDataStore)
    }

    fn populate_repo(repo: &mut Repository) {
        block_on(
            repo.data_store.save_thing(
                &Place {
                    uuid: OLYMPUS_UUID,
                    data: PlaceData {
                        location_uuid: THESSALY_UUID.into(),
                        name: "Olympus".into(),
                        ..Default::default()
                    },
                }
                .into(),
            ),
        )
        .unwrap();
        block_on(
            repo.data_store.save_thing(
                &Place {
                    uuid: THESSALY_UUID,
                    data: PlaceData {
                        location_uuid: GREECE_UUID.into(),
                        name: "Thessaly".into(),
                        ..Default::default()
                    },
                }
                .into(),
            ),
        )
        .unwrap();
        block_on(
            repo.data_store.save_thing(
                &Place {
                    uuid: GREECE_UUID,
                    data: PlaceData {
                        name: "Greece".into(),
                        ..Default::default()
                    },
                }
                .into(),
            ),
        )
        .unwrap();
        block_on(
            repo.data_store.save_thing(
                &Place {
                    uuid: STYX_UUID,
                    data: PlaceData {
                        location_uuid: Uuid::nil().into(),
                        name: "River Styx".into(),
                        ..Default::default()
                    },
                }
                .into(),
            ),
        )
        .unwrap();

        repo.recent.push_back(
            Npc {
                uuid: ODYSSEUS_UUID,
                data: NpcData {
                    name: "Odysseus".into(),
                    location_uuid: STYX_UUID.into(),
                    ..Default::default()
                },
            }
            .into(),
        );

        block_on(repo.init());
    }

    struct TimeBombDataStore {
        t_minus: Rc<RefCell<usize>>,
        data_store: MemoryDataStore,
    }

    impl TimeBombDataStore {
        pub fn new(t_minus: usize) -> Self {
            Self {
                t_minus: Rc::new(t_minus.into()),
                data_store: MemoryDataStore::default(),
            }
        }

        fn tick(&self) -> Result<(), ()> {
            if *self.t_minus.borrow() == 0 {
                Err(())
            } else {
                self.t_minus.replace_with(|&mut i| i - 1);
                Ok(())
            }
        }
    }

    #[async_trait(?Send)]
    impl DataStore for TimeBombDataStore {
        async fn health_check(&self) -> Result<(), ()> {
            if *self.t_minus.borrow() == 0 {
                Err(())
            } else {
                Ok(())
            }
        }

        async fn delete_thing_by_uuid(&mut self, uuid: &Uuid) -> Result<(), ()> {
            self.tick()?;
            self.data_store.delete_thing_by_uuid(uuid).await
        }

        async fn edit_thing(&mut self, thing: &Thing) -> Result<(), ()> {
            self.tick()?;
            self.data_store.edit_thing(thing).await
        }

        async fn get_all_the_things(&self) -> Result<Vec<Thing>, ()> {
            self.tick()?;
            self.data_store.get_all_the_things().await
        }

        async fn get_thing_by_uuid(&self, uuid: &Uuid) -> Result<Option<Thing>, ()> {
            self.tick()?;
            self.data_store.get_thing_by_uuid(uuid).await
        }

        async fn get_thing_by_name(&self, name: &str) -> Result<Option<Thing>, ()> {
            self.tick()?;
            self.data_store.get_thing_by_name(name).await
        }

        async fn get_things_by_name_start(
            &self,
            name: &str,
            limit: Option<usize>,
        ) -> Result<Vec<Thing>, ()> {
            self.tick()?;
            self.data_store.get_things_by_name_start(name, limit).await
        }

        async fn save_thing(&mut self, thing: &Thing) -> Result<(), ()> {
            self.tick()?;
            self.data_store.save_thing(thing).await
        }

        async fn set_value(&mut self, key: &str, value: &str) -> Result<(), ()> {
            self.tick()?;
            self.data_store.set_value(key, value).await
        }

        async fn get_value(&self, key: &str) -> Result<Option<String>, ()> {
            self.tick()?;
            self.data_store.get_value(key).await
        }

        async fn delete_value(&mut self, key: &str) -> Result<(), ()> {
            self.tick()?;
            self.data_store.delete_value(key).await
        }
    }
}