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
use super::*;
use chrono::prelude::{DateTime, Utc};

// ----------------------------------------------------------------------------
#[derive(Serialize, Deserialize, Debug, Clone, Default, Eq, Hash)]
/// Category of an asset. It provides two ways to categorise assets, one is less
/// flexible, and the other is more flexible:
///   - By [`Semantic`], i.e. what the asset is conventionally thought to belong to, e.g. props, vehicle, etc.
///   - By [`Criterion`], a more descriptive method to group assets, by having a separate set of methods to
/// interact with the criterion definition.
///
/// LEGACY DESIGN: DO NOT change field names or `serde(rename)` values.
pub struct AssetCategory {
    #[serde(skip)]
    /// Richer type of `Self::semantic_str`.
    semantic: Semantic,

    /// Original way to group assets by their "general idea", e.g. "vehicles".
    /// This correlates with "category.main_type" field in `MongoDB` asset documents.
    #[serde(rename = "main_type", skip_serializing_if = "Option::is_none")]
    semantic_str: Option<String>,

    /// New addition to the system that acts as a way to group assets.
    /// This is treated as precedence over `Self::semantic`.
    /// The `ObjectId`s refer to [`Criterion`]s.
    #[serde(skip_serializing_if = "Option::is_none")]
    criteria: Option<Vec<ObjectId>>,
}

impl AssetCategory {
    // Semantic-related

    pub fn from_semantic(sem: &Semantic) -> Self {
        Self {
            // NOTE: must populate `Self::semantic_str`
            semantic_str: Some(sem.to_string()),
            semantic: sem.to_owned(),
            ..Self::empty()
        }
    }

    pub fn empty() -> Self {
        Self {
            semantic: Semantic::Other(None),
            semantic_str: None,
            criteria: None,
        }
    }

    pub fn semantic(&self) -> &Semantic {
        &self.semantic
    }

    pub fn is_semantic_empty(&self) -> bool {
        self.semantic_str.is_none()
    }

    /// Maps
    pub fn semantic_mut_from_str(&mut self) {
        self.semantic = match &self.semantic_str {
            None => Semantic::Other(None),
            Some(sem) => sem.as_str().into(),
        };
    }

    // Criteria-related

    pub fn criteria(&self) -> Option<&Vec<ObjectId>> {
        self.criteria.as_ref()
    }

    pub fn with_criteria(mut self, criteria: &[&ObjectId]) -> Self {
        self.criteria = Some(criteria.to_vec().into_iter().map(|id| id.clone()).collect());
        self
    }

    pub fn is_criteria_empty(&self) -> bool {
        self.criteria.is_none()
    }

    /// Can be used as optimization for [`AssetExcerpt`].
    pub fn take_criteria(mut self) -> Self {
        self.criteria.take();
        self
    }
}

impl PartialEq for AssetCategory {
    fn eq(&self, other: &Self) -> bool {
        self.semantic == other.semantic
    }
}
impl Ord for AssetCategory {
    fn cmp(&self, other: &Self) -> Ordering {
        self.semantic.cmp(&other.semantic)
    }
}
impl PartialOrd for AssetCategory {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

// ----------------------------------------------------------------------------
#[derive(
    Deserialize_repr,
    Serialize_repr,
    Debug,
    Clone,
    Default,
    Hash,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    strum::AsRefStr,
    strum::EnumIter,
)]
#[repr(u8)]
pub enum CriterionType {
    #[default]
    Batch = 0,
    // Expense = 1,
}

#[cfg(feature = "gui")]
fn show_criterion_type_options(ui: &mut egui::Ui, typ: &mut CriterionType) {
    ui.horizontal(|ui| {
        ui.label("Type:");
        for t in CriterionType::iter() {
            if ui
                .add(egui::SelectableLabel::new(*typ == t, t.as_ref()))
                .clicked()
            {
                *typ = t;
            }
        }
    });
}

// ----------------------------------------------------------------------------
#[derive(Debug, Clone, Hash, Eq, Ord)]
#[cfg_attr(feature = "mongo", derive(Serialize, Deserialize))]
pub struct Criterion {
    #[cfg_attr(feature = "mongo", serde(skip))]
    mode: MediaMode,

    #[cfg_attr(
        feature = "mongo",
        serde(rename = "_id", skip_serializing_if = "Option::is_none")
    )]
    id: Option<ObjectId>,

    name: String,

    typ: CriterionType,

    active: bool,

    #[cfg_attr(feature = "mongo", serde(skip))]
    forbid_active_mut: bool,

    #[cfg_attr(
        feature = "mongo",
        serde(with = "bson::serde_helpers::chrono_datetime_as_bson_datetime")
    )]
    created_at: DateTime<Utc>,

    #[cfg_attr(
        feature = "mongo",
        serde(with = "bson::serde_helpers::chrono_datetime_as_bson_datetime")
    )]
    updated_at: DateTime<Utc>,

    comment: String,
}

impl Criterion {
    pub fn empty() -> Self {
        Self {
            mode: MediaMode::default(),
            id: None,
            name: String::new(),
            typ: CriterionType::default(),
            active: true,
            forbid_active_mut: false,
            created_at: Utc::now(),
            updated_at: Utc::now(),
            comment: String::new(),
        }
    }

    pub fn new(name: &str) -> Self {
        Self {
            name: name.to_owned(),
            ..Self::empty()
        }
    }

    pub fn owned_name(self) -> String {
        self.name
    }

    pub fn name(&self) -> &String {
        &self.name
    }

    pub fn comment(mut self, cmt: &str) -> Self {
        self.comment = cmt.to_owned();
        self
    }

    pub fn created_now(&mut self) {
        self.created_at = Utc::now();
    }

    pub fn updated_now(&mut self) {
        self.updated_at = Utc::now();
    }

    #[cfg(feature = "gui")]
    /// Depending on `Self::mode` to show the UI for reading, or the UI for editing.
    pub fn ui(&mut self, ui: &mut egui::Ui) {
        match &self.mode {
            MediaMode::Read => self.read_mode_ui(ui),
            MediaMode::WriteSuggest => {
                self.write_suggest_ui(ui);
            }
            MediaMode::WriteCompose => {
                self.write_compose_ui(ui);
            }
            MediaMode::WriteEdit => {
                self.write_edit_ui(ui);
            }
        }
    }
}

impl BsonId for Criterion {
    fn bson_id_as_ref(&self) -> Option<&ObjectId> {
        self.id.as_ref()
    }

    fn bson_id(&self) -> AnyResult<&ObjectId> {
        self.id.as_ref().context("Criterion without BSON ObjectId")
    }
}

impl PartialEq for Criterion {
    fn eq(&self, other: &Self) -> bool {
        self.id == other.id
    }
}

impl PartialOrd for Criterion {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        self.id.partial_cmp(&other.id)
    }
}

impl ReadWriteSuggest for Criterion {
    /// The draft [`Criterion`] shouldn't show the `Self::active` checkbox switch.
    fn write_suggest() -> Self {
        let mut crit = Self::empty().with_mode(MediaMode::WriteSuggest);
        crit.forbid_active_mut = true;
        crit
    }

    fn with_mode(mut self, mode: MediaMode) -> Self {
        self.mode_mut(mode);
        self
    }

    fn mode(&self) -> &MediaMode {
        &self.mode
    }

    fn mode_mut(&mut self, mode: MediaMode) {
        self.mode = mode;
    }

    #[cfg(feature = "gui")]
    fn read_mode_ui(&mut self, ui: &mut egui::Ui) {
        ui.group(|ui| {
            ui.vertical(|ui| {
                match self.active {
                    true => {
                        // Name
                        ui.heading(&self.name);
                        // Comment
                        ui.label(&self.comment);
                    }
                    false => {
                        // Name
                        ui.label(
                            RichText::new(format!("[Deactivated] {}", &self.name))
                                .heading()
                                .weak(),
                        );
                        // Comment
                        ui.weak(&self.comment);
                    }
                };
            });
        });
    }

    #[cfg(feature = "gui")]
    fn write_suggest_ui(&mut self, ui: &mut egui::Ui) {
        ui.vertical_centered(|ui| {
            if ui
                .button(RichText::new("➕ New").heading())
                .on_hover_text("Draft a new category")
                .clicked()
            {
                self.mode = MediaMode::WriteCompose;
            };
        });
    }

    #[cfg(feature = "gui")]
    fn write_compose_ui(&mut self, ui: &mut egui::Ui) {
        ui.group(|ui| {
            // `egui::Grid` won't show the `egui::TextEdit` with `desired_width`.
            ui.vertical(|ui| {
                // TODO: work with `Self::active"
                // if !self.forbid_active_mut {
                //     ui.checkbox(&mut self.active, "Active");
                // };
                show_criterion_type_options(ui, &mut self.typ);
                ui.horizontal(|ui| {
                    // Name
                    ui.monospace("Name:   ");
                    ui.add(
                        egui::TextEdit::singleline(&mut self.name)
                            .hint_text("Name of the new category, e.g. Batch 3")
                            .desired_width(300.),
                    );
                });
                ui.horizontal(|ui| {
                    // Comment
                    ui.monospace("Comment:");
                    ui.add(egui::TextEdit::singleline(&mut self.comment).desired_width(300.));
                });
            });
        });
    }
}

impl BsonId for &Criterion {
    fn bson_id_as_ref(&self) -> Option<&ObjectId> {
        self.id.as_ref()
    }

    fn bson_id(&self) -> AnyResult<&ObjectId> {
        self.id.as_ref().context("Criterion without BSON ObjectId")
    }
}
// ----------------------------------------------------------------------------
#[derive(Debug, Clone, Default)]
pub struct CriterionOptions {
    /// Handle to Box<dyn [`MakeCriteria`]> to fetch a project's [`Criterion`]s upon refresh.
    pub dbi: Option<Box<dyn MakeCriteria>>,
    /// All available [`Criterion`]s found within the current [`Project`].
    pub active: Vec<Criterion>,
    /// This keeps track of the selected criteria.
    pub select_state: BTreeSet<Criterion>,
}

impl CriterionOptions {
    #[cfg(feature = "gui")]
    /// Shows checkboxes to select a subset of all active [`Criterion`]s of the current [`Project`].
    pub fn select_criteria_ui(&mut self, ui: &mut egui::Ui) {
        for c in self.active.iter() {
            let mut selected = self.select_state.contains(c);
            ui.checkbox(&mut selected, c.name())
                .on_hover_text(&c.comment);
            toggle_criterion(&mut self.select_state, c, selected);
        }
    }

    pub fn selected_bson_ids(&self) -> Vec<&ObjectId> {
        self.select_state
            .iter()
            .filter_map(|c| c.id.as_ref())
            .collect()
    }
}

// ----------------------------------------------------------------------------
#[derive(
    Deserialize,
    Serialize,
    Debug,
    Clone,
    PartialEq,
    Eq,
    Hash,
    PartialOrd,
    Ord,
    strum::AsRefStr,
    strum::EnumIter,
)]
/// "Main type" of an asset category.
/// LEGACY DESIGN: DO NOT change enum names or `strum::AsRefStr` values -- if any.
/// `non_camel_case_types` is required for deserialization of existing data.
pub enum Semantic {
    #[strum(serialize = "char")]
    Character,
    #[strum(serialize = "prop")]
    Prop,
    #[strum(serialize = "vehicles")]
    Vehicle,
    #[strum(serialize = "set")]
    Set,
    #[strum(serialize = "setdress")]
    SetDress,
    #[strum(serialize = "fx")]
    Fx,
    #[strum(serialize = "env")]
    Env,
    #[strum(serialize = "cam")]
    Camera,
    #[strum(serialize = "scinsert")]
    ScInsert,
    #[strum(serialize = "location")]
    Location,
    #[strum(serialize = "sector")]
    Sector,
    #[strum(serialize = "dmp")]
    Dmp,
    Other(Option<String>),
}

impl Default for Semantic {
    fn default() -> Self {
        Self::Other(None)
    }
}

impl Semantic {
    pub fn to_string(&self) -> String {
        let repr = match self {
            Self::Other(Some(typ)) => typ,
            // Self::Other(None) will be "Other"
            _ => self.as_ref(),
        };
        repr.to_owned()
    }
}

#[cfg(feature = "gui")]
pub fn semantic_options_ui(ui: &mut egui::Ui, sem: &mut Semantic) {
    egui::ComboBox::from_label("Group")
        .selected_text(sem.as_ref())
        .show_ui(ui, |ui| {
            for s in Semantic::iter() {
                if let Semantic::Other(_) = s {
                    // not supporting `Semantic::Other(_)`
                    continue;
                } else {
                    if ui.selectable_label(sem == &s, s.as_ref()).clicked() {
                        *sem = s;
                    };
                }
            }
        });
}

impl From<&str> for Semantic {
    fn from(typ: &str) -> Self {
        match typ {
            "char" => Self::Character,
            "prop" => Self::Prop,
            "vehicles" => Self::Vehicle,
            "set" => Self::Set,
            "setdress" => Self::SetDress,
            "fx" => Self::Fx,
            "env" => Self::Env,
            "cam" => Self::Camera,
            "scinsert" => Self::ScInsert,
            "location" => Self::Location,
            "sector" => Self::Sector,
            "dmp" => Self::Dmp,
            _ => Self::Other(Some(typ.to_owned())),
        }
    }
}

// ----------------------------------------------------------------------------
#[async_trait]
/// Interface to how CRUD for [`Criterion`] is handled.
pub trait MakeCriteria: DynClone + fmt::Debug + Send + Sync {
    /// Gets all the criteria of the [`Project`].
    async fn criteria(&self, project: &Project) -> Result<Vec<Criterion>, DatabaseError>;

    /// Adds a new criterion for the [`Project`].
    async fn add_criterion(
        &self,
        project: &Project,
        crit: &Criterion,
    ) -> Result<(), ModificationError>;

    /// Deletes an existing criterion from the [`Project`].
    async fn delete_criterion(
        &self,
        project: &Project,
        crit: &Criterion,
    ) -> Result<(), ModificationError>;

    /// Updates an existing criterion in the [`Project`].
    async fn update_criterion(
        &self,
        project: &Project,
        existing: Option<&Criterion>,
        updated: &Criterion,
    ) -> Result<(), ModificationError>;

    /// Assigns the given [`Criterion`] to the given [`ProductionAsset`]s of the [`Project`].
    async fn assign_criterion(
        &self,
        project: &Project,
        assets: &[ProductionAsset],
        crit: &Criterion,
    ) -> Result<(), ModificationError>;

    /// Unassigns the given [`Criterion`] for the given [`ProductionAsset`]s of the [`Project`].
    async fn unassign_criterion(
        &self,
        project: &Project,
        assets: &[ProductionAsset],
        crit: &Criterion,
    ) -> Result<(), ModificationError>;

    /// Gets all the `ProductionAssets` which have been assigned the given [`Criterion`].
    async fn assigned_assets(
        &self,
        project: &Project,
        crit: &Criterion,
    ) -> Result<Vec<ProductionAsset>, DatabaseError>;

    /// Removes all [`Criterion`] assignments in all [`ProductionAsset`]s of the [`Project`].
    async fn obliterate_assignments(&self, project: &Project) -> Result<(), ModificationError>;
}

dyn_clone::clone_trait_object!(MakeCriteria);

// ----------------------------------------------------------------------------
#[cfg(feature = "gui")]
fn toggle_criterion(select_state: &mut BTreeSet<Criterion>, crit: &Criterion, selected: bool) {
    if selected {
        if !select_state.contains(crit) {
            select_state.insert(crit.to_owned());
        }
    } else {
        select_state.remove(crit);
    }
}

#[cfg(test)]
mod tests {}