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
use super::{Demographics, Field, Generate};
use crate::world::command::ParsedThing;
use crate::world::npc::{DetailsView as NpcDetailsView, Gender, Npc, NpcData, NpcRelations};
use crate::world::place::{DetailsView as PlaceDetailsView, Place, PlaceData, PlaceRelations};
use rand::Rng;
use serde::{Deserialize, Serialize};
use std::cmp::Ordering;
use std::fmt;
use std::str::FromStr;
use uuid::Uuid;

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct Thing {
    pub uuid: Uuid,

    #[serde(flatten)]
    pub data: ThingData,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(tag = "type")]
pub enum ThingData {
    Npc(NpcData),
    Place(PlaceData),
}

#[derive(Debug, Default)]
pub enum ThingRelations {
    #[default]
    None,
    Npc(NpcRelations),
    Place(PlaceRelations),
}

pub struct SummaryView<'a>(&'a ThingData);

pub struct DescriptionView<'a>(&'a ThingData);

pub enum DetailsView<'a> {
    Npc(NpcDetailsView<'a>),
    Place(PlaceDetailsView<'a>),
}

impl Thing {
    pub fn name(&self) -> &Field<String> {
        self.data.name()
    }

    pub fn as_str(&self) -> &'static str {
        self.data.as_str()
    }

    pub fn regenerate(&mut self, rng: &mut impl Rng, demographics: &Demographics) {
        self.data.regenerate(rng, demographics)
    }

    pub fn gender(&self) -> Gender {
        self.data.gender()
    }

    pub fn display_summary(&self) -> SummaryView {
        self.data.display_summary()
    }

    pub fn display_description(&self) -> DescriptionView {
        self.data.display_description()
    }

    pub fn display_details(&self, relations: ThingRelations) -> DetailsView {
        self.data.display_details(self.uuid, relations)
    }

    pub fn lock_all(&mut self) {
        self.data.lock_all()
    }

    #[expect(clippy::result_unit_err)]
    pub fn try_apply_diff(&mut self, diff: &mut ThingData) -> Result<(), ()> {
        self.data.try_apply_diff(diff)
    }
}

impl ThingData {
    pub fn name(&self) -> &Field<String> {
        match &self {
            ThingData::Place(place) => &place.name,
            ThingData::Npc(npc) => &npc.name,
        }
    }

    pub fn as_str(&self) -> &'static str {
        match self {
            ThingData::Place(..) => "place",
            ThingData::Npc(..) => "character",
        }
    }

    pub fn regenerate(&mut self, rng: &mut impl Rng, demographics: &Demographics) {
        match self {
            ThingData::Place(place) => place.regenerate(rng, demographics),
            ThingData::Npc(npc) => npc.regenerate(rng, demographics),
        }
    }
    pub fn gender(&self) -> Gender {
        if let Self::Npc(npc) = self {
            npc.gender()
        } else {
            Gender::Neuter
        }
    }

    pub fn place_data(&self) -> Option<&PlaceData> {
        if let Self::Place(place) = self {
            Some(place)
        } else {
            None
        }
    }

    pub fn npc_data(&self) -> Option<&NpcData> {
        if let Self::Npc(npc) = self {
            Some(npc)
        } else {
            None
        }
    }

    pub fn display_summary(&self) -> SummaryView {
        SummaryView(self)
    }

    pub fn display_description(&self) -> DescriptionView {
        DescriptionView(self)
    }

    pub fn display_details(&self, uuid: Uuid, relations: ThingRelations) -> DetailsView {
        match self {
            Self::Npc(npc) => DetailsView::Npc(npc.display_details(uuid, relations.into())),
            Self::Place(place) => DetailsView::Place(place.display_details(uuid, relations.into())),
        }
    }

    pub fn lock_all(&mut self) {
        match self {
            Self::Npc(npc) => npc.lock_all(),
            Self::Place(place) => place.lock_all(),
        }
    }

    pub fn try_apply_diff(&mut self, diff: &mut Self) -> Result<(), ()> {
        match (self, diff) {
            (Self::Npc(npc), Self::Npc(diff_npc)) => npc.apply_diff(diff_npc),
            (Self::Place(place), Self::Place(diff_place)) => place.apply_diff(diff_place),
            _ => return Err(()),
        }

        Ok(())
    }
}

impl From<Npc> for Thing {
    fn from(npc: Npc) -> Self {
        Thing {
            uuid: npc.uuid,
            data: npc.data.into(),
        }
    }
}

impl From<Place> for Thing {
    fn from(place: Place) -> Self {
        Thing {
            uuid: place.uuid,
            data: place.data.into(),
        }
    }
}

impl TryFrom<Thing> for Npc {
    type Error = Thing;

    fn try_from(thing: Thing) -> Result<Self, Self::Error> {
        if let ThingData::Npc(npc) = thing.data {
            Ok(Npc {
                uuid: thing.uuid,
                data: npc,
            })
        } else {
            Err(thing)
        }
    }
}

impl TryFrom<Thing> for Place {
    type Error = Thing;

    fn try_from(thing: Thing) -> Result<Self, Self::Error> {
        if let ThingData::Place(place) = thing.data {
            Ok(Place {
                uuid: thing.uuid,
                data: place,
            })
        } else {
            Err(thing)
        }
    }
}

impl From<NpcData> for ThingData {
    fn from(npc: NpcData) -> Self {
        ThingData::Npc(npc)
    }
}

impl From<PlaceData> for ThingData {
    fn from(place: PlaceData) -> Self {
        ThingData::Place(place)
    }
}

impl TryFrom<ThingData> for NpcData {
    type Error = ThingData;

    fn try_from(thing_data: ThingData) -> Result<Self, Self::Error> {
        if let ThingData::Npc(npc) = thing_data {
            Ok(npc)
        } else {
            Err(thing_data)
        }
    }
}

impl TryFrom<ThingData> for PlaceData {
    type Error = ThingData;

    fn try_from(thing_data: ThingData) -> Result<Self, Self::Error> {
        if let ThingData::Place(place) = thing_data {
            Ok(place)
        } else {
            Err(thing_data)
        }
    }
}

impl From<NpcRelations> for ThingRelations {
    fn from(input: NpcRelations) -> Self {
        Self::Npc(input)
    }
}

impl From<PlaceRelations> for ThingRelations {
    fn from(input: PlaceRelations) -> Self {
        Self::Place(input)
    }
}

impl From<ThingRelations> for NpcRelations {
    fn from(input: ThingRelations) -> Self {
        if let ThingRelations::Npc(npc) = input {
            npc
        } else {
            NpcRelations::default()
        }
    }
}

impl From<ThingRelations> for PlaceRelations {
    fn from(input: ThingRelations) -> Self {
        if let ThingRelations::Place(place) = input {
            place
        } else {
            PlaceRelations::default()
        }
    }
}

impl FromStr for ParsedThing<ThingData> {
    type Err = ();

    fn from_str(raw: &str) -> Result<Self, Self::Err> {
        match (
            raw.parse::<ParsedThing<NpcData>>(),
            raw.parse::<ParsedThing<PlaceData>>(),
        ) {
            (Ok(parsed_npc), Ok(parsed_place)) => match parsed_npc
                .unknown_words
                .len()
                .cmp(&parsed_place.unknown_words.len())
            {
                Ordering::Less => Ok(parsed_npc.into_thing_data()),
                Ordering::Equal => Err(()),
                Ordering::Greater => Ok(parsed_place.into_thing_data()),
            },
            (Ok(parsed_npc), Err(())) => Ok(parsed_npc.into_thing_data()),
            (Err(()), Ok(parsed_place)) => Ok(parsed_place.into_thing_data()),
            (Err(()), Err(())) => Err(()),
        }
    }
}

impl<'a> fmt::Display for SummaryView<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.0 {
            ThingData::Place(l) => write!(f, "{}", l.display_summary()),
            ThingData::Npc(n) => write!(f, "{}", n.display_summary()),
        }
    }
}

impl<'a> fmt::Display for DescriptionView<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.0 {
            ThingData::Place(l) => write!(f, "{}", l.display_description()),
            ThingData::Npc(n) => write!(f, "{}", n.display_description()),
        }
    }
}

impl<'a> fmt::Display for DetailsView<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            DetailsView::Npc(view) => write!(f, "{}", view),
            DetailsView::Place(view) => write!(f, "{}", view),
        }
    }
}

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

    #[test]
    fn name_test() {
        {
            let mut place = PlaceData::default();
            place.name.replace("The Prancing Pony".to_string());
            assert_eq!(
                Some(&"The Prancing Pony".to_string()),
                ThingData::from(place).name().value()
            );
        }

        {
            let mut npc = NpcData::default();
            npc.name.replace("Frodo Underhill".to_string());
            assert_eq!(
                Some(&"Frodo Underhill".to_string()),
                ThingData::from(npc).name().value()
            );
        }
    }

    #[test]
    fn into_test() {
        assert!(matches!(PlaceData::default().into(), ThingData::Place(_)));
        assert!(matches!(NpcData::default().into(), ThingData::Npc(_)));
    }

    #[test]
    fn serialize_deserialize_test_place() {
        let thing = place();
        assert_eq!(
            r#"{"uuid":"00000000-0000-0000-0000-000000000000","type":"Place","location_uuid":null,"subtype":null,"name":null,"description":null}"#,
            serde_json::to_string(&thing).unwrap(),
        );
    }

    #[test]
    fn serialize_deserialize_test_npc() {
        let thing = npc();
        assert_eq!(
            r#"{"uuid":"00000000-0000-0000-0000-000000000000","type":"Npc","name":null,"gender":null,"age":null,"age_years":null,"size":null,"species":null,"ethnicity":null,"location_uuid":null}"#,
            serde_json::to_string(&thing).unwrap(),
        );
    }

    #[test]
    fn place_npc_test() {
        {
            let thing = place();
            assert!(thing.data.place_data().is_some());
            assert!(thing.data.npc_data().is_none());
            assert!(PlaceData::try_from(thing.data.clone()).is_ok());
            assert!(NpcData::try_from(thing.data.clone()).is_err());
            assert!(Place::try_from(thing.clone()).is_ok());
            assert!(Npc::try_from(thing).is_err());
        }

        {
            let thing = npc();
            assert!(thing.data.npc_data().is_some());
            assert!(thing.data.place_data().is_none());
            assert!(NpcData::try_from(thing.data.clone()).is_ok());
            assert!(PlaceData::try_from(thing.data.clone()).is_err());
            assert!(Npc::try_from(thing.clone()).is_ok());
            assert!(Place::try_from(thing).is_err());
        }
    }

    #[test]
    fn gender_test() {
        assert_eq!(Gender::Neuter, place().gender());
        assert_eq!(Gender::NonBinaryThey, npc().gender());

        let npc = ThingData::Npc(NpcData {
            gender: Gender::Feminine.into(),
            ..Default::default()
        });

        assert_eq!(Gender::Feminine, npc.gender());
    }

    #[test]
    fn lock_all_test_npc() {
        let mut npc = NpcData::default();
        npc.lock_all();
        let mut thing = ThingData::Npc(NpcData::default());
        thing.lock_all();
        assert_eq!(ThingData::Npc(npc), thing);
    }

    #[test]
    fn lock_all_test_place() {
        let mut place = PlaceData::default();
        place.lock_all();
        let mut thing = ThingData::Place(PlaceData::default());
        thing.lock_all();
        assert_eq!(ThingData::Place(place), thing);
    }

    fn place() -> Thing {
        Thing {
            uuid: Uuid::nil(),
            data: ThingData::Place(PlaceData::default()),
        }
    }

    fn npc() -> Thing {
        Thing {
            uuid: Uuid::nil(),
            data: ThingData::Npc(NpcData::default()),
        }
    }
}