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
//! TODO: Maybe this file is too small

use alloc::collections::btree_map::Entry::*;
use alloc::collections::BTreeMap;
use alloc::string::ToString;
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::{fmt, mem};

use crate::behavior::{self, BehaviorSetTransaction};
use crate::block::Block;
use crate::drawing::DrawingPlane;
use crate::fluff::Fluff;
use crate::math::{Cube, GridCoordinate, GridPoint, Gridgid};
use crate::space::{ActivatableRegion, GridAab, SetCubeError, Space};
use crate::transaction::{
    self, no_outputs, CommitError, Merge, NoOutput, Transaction, Transactional,
};
use crate::util::{ConciseDebug, Refmt as _};

#[cfg(doc)]
use crate::behavior::BehaviorSet;

impl Transactional for Space {
    type Transaction = SpaceTransaction;
}

/// A [`Transaction`] that modifies a [`Space`].
#[derive(Clone, Default, Eq, PartialEq)]
#[must_use]
pub struct SpaceTransaction {
    cubes: BTreeMap<[GridCoordinate; 3], CubeTransaction>,
    behaviors: BehaviorSetTransaction<Space>,
}

impl SpaceTransaction {
    /// Allows modifying the part of this transaction which is a [`CubeTransaction`] at the given
    /// cube, creating it if necessary (as [`CubeTransaction::default()`]).
    ///
    /// You can replace the transaction or use [`CubeTransaction::merge_from()`] to merge in
    /// another transaction.
    ///
    /// This is for incremental construction of a complex transaction;
    /// to create a transaction affecting a single cube, [`CubeTransaction::at()`] will be more
    /// convenient.
    pub fn at(&mut self, cube: Cube) -> &mut CubeTransaction {
        let cube: GridPoint = cube.into();
        self.cubes.entry(cube.into()).or_default()
    }

    /// Construct a [`SpaceTransaction`] which modifies a volume by applying a [`CubeTransaction`]
    /// computed by `function` to each cube.
    pub fn filling<F>(region: GridAab, mut function: F) -> Self
    where
        F: FnMut(Cube) -> CubeTransaction,
    {
        // TODO: Try having a compact `Vol<Box<[CubeTransaction]>>` representation for this kind of
        // transaction with uniformly shaped contents.
        let mut txn = SpaceTransaction::default();
        for cube in region.interior_iter() {
            *txn.at(cube) = function(cube);
        }
        txn
    }

    /// Construct a [`SpaceTransaction`] for a single cube.
    ///
    /// If `old` is not [`None`], requires that the existing block is that block or the
    /// transaction will fail.
    /// If `new` is not [`None`], replaces the existing block with `new`.
    ///
    /// TODO: Consider replacing all uses of this with `CubeTransaction::replacing()`.
    pub fn set_cube(cube: impl Into<Cube>, old: Option<Block>, new: Option<Block>) -> Self {
        CubeTransaction::replacing(old, new).at(cube.into())
    }

    /// Provides an [`DrawTarget`](embedded_graphics::prelude::DrawTarget)
    /// adapter for 2.5D drawing.
    ///
    /// For more information on how to use this, see
    /// [`all_is_cubes::drawing`](crate::drawing).
    pub fn draw_target<C>(&mut self, transform: Gridgid) -> DrawingPlane<'_, Self, C> {
        DrawingPlane::new(self, transform)
    }

    /// Marks all cube modifications in this transaction as [non-conservative].
    ///
    /// This means that two transactions which both place the same block in a given cube
    /// may be merged, whereas the default state is that they will conflict (on the
    /// principle that such a merge could cause there to be fewer total occurrences of
    /// that block than intended).
    ///
    /// Also, the transaction will not fail if some of its cubes are outside the bounds of
    /// the [`Space`].
    ///
    /// [non-conservative]: https://en.wikipedia.org/wiki/Conserved_quantity
    pub fn nonconserved(mut self) -> Self {
        for (_, cube_txn) in self.cubes.iter_mut() {
            cube_txn.conserved = false;
        }
        self
    }

    /// Modify the space's [`BehaviorSet`].
    pub fn behaviors(t: BehaviorSetTransaction<Space>) -> Self {
        Self {
            behaviors: t,
            ..Default::default()
        }
    }

    /// Add a behavior to the [`Space`].
    /// This is a shortcut for creating a [`BehaviorSetTransaction`].
    pub fn add_behavior<B>(bounds: GridAab, behavior: B) -> Self
    where
        B: behavior::Behavior<Space> + 'static,
    {
        Self::behaviors(BehaviorSetTransaction::insert(
            super::SpaceBehaviorAttachment::new(bounds),
            Arc::new(behavior),
        ))
    }

    /// Computes the region of cubes directly affected by this transaction.
    /// Ignores behaviors.
    ///
    /// Returns [`None`] if no cubes are affected.
    ///
    /// TODO: Handle the case where the total volume is too large.
    /// (Maybe `GridAab` should lose that restriction.)
    pub fn bounds_only_cubes(&self) -> Option<GridAab> {
        // Destructuring to statically check that we consider all fields.
        let Self {
            cubes,
            behaviors: _,
        } = self;
        let mut bounds: Option<GridAab> = None;

        for &cube_array in cubes.keys() {
            let cube = Cube::from(cube_array);
            if let Some(bounds) = &mut bounds {
                *bounds = (*bounds).union_cube(cube);
            } else {
                bounds = Some(GridAab::single_cube(cube));
            }
        }

        bounds
    }

    /// Computes the region affected by this transaction.
    ///
    /// Returns [`None`] if no specific regions of the space are affected.
    pub fn bounds(&self) -> Option<GridAab> {
        // Destructuring to statically check that we consider all fields.
        let Self {
            cubes: _,
            behaviors,
        } = self;
        let mut bounds: Option<GridAab> = self.bounds_only_cubes();

        for attachment in behaviors.attachments_affected() {
            if let Some(bounds) = &mut bounds {
                *bounds = (*bounds).union_box(attachment.bounds);
            } else {
                bounds = Some(attachment.bounds);
            }
        }

        bounds
    }
}

impl Transaction for SpaceTransaction {
    type Target = Space;
    type CommitCheck = <BehaviorSetTransaction<Space> as Transaction>::CommitCheck;
    type Output = NoOutput;
    type Mismatch = SpaceTransactionMismatch;

    fn check(&self, space: &Space) -> Result<Self::CommitCheck, Self::Mismatch> {
        for (
            &cube,
            CubeTransaction {
                old,
                new: _,
                conserved,
                activate_behavior: _,
                fluff: _,
            },
        ) in &self.cubes
        {
            let cube = Cube::from(cube);
            if let Some(cube_index) = space.contents.index(cube) {
                if let Some(old) = old {
                    // Raw lookup because we already computed the index for a bounds check
                    // (TODO: Put this in a function, like get_block_index)
                    if space
                        .palette
                        .entry(space.contents.as_linear()[cube_index])
                        .block()
                        != old
                    {
                        return Err(SpaceTransactionMismatch::Cube(cube));
                    }
                }
            } else {
                if *conserved || old.is_some() {
                    // It is an error for conserved cube txns to be out of bounds,
                    // or for a precondition to be not meetable because it is out of bounds.
                    // TODO: Should we allow `old: Some(AIR), new: None`, since we treat
                    // outside-space as being AIR? Let's wait until a use case appears rather than
                    // making AIR more special.
                    return Err(SpaceTransactionMismatch::OutOfBounds {
                        transaction: cube.grid_aab(),
                        space: space.bounds(),
                    });
                }
            }
        }
        self.behaviors
            .check(&space.behaviors)
            .map_err(SpaceTransactionMismatch::Behaviors)
    }

    fn commit(
        &self,
        space: &mut Space,
        check: Self::CommitCheck,
        _outputs: &mut dyn FnMut(Self::Output),
    ) -> Result<(), CommitError> {
        let mut to_activate = Vec::new();

        // Create a mutation context, which lets us batch change notifications from this commit.
        let mut ctx = crate::space::MutationCtx {
            palette: &mut space.palette,
            contents: space.contents.as_mut(),
            light: &mut space.light,
            change_buffer: &mut space.change_notifier.buffer(),
            cubes_wanting_ticks: &mut space.cubes_wanting_ticks,
        };

        for (
            &cube,
            CubeTransaction {
                old: _,
                new,
                conserved,
                activate_behavior: activate,
                fluff,
            },
        ) in &self.cubes
        {
            let cube = Cube::from(cube);

            if let Some(new) = new {
                match Space::set_impl(&mut ctx, cube, new) {
                    Ok(_) => Ok(()),
                    Err(SetCubeError::OutOfBounds { .. }) if !conserved => {
                        // ignore
                        Ok(())
                    }
                    Err(other) => Err(CommitError::catch::<Self, _>(other)),
                }?;
            }

            if *activate {
                // Deferred for slightly more consistency
                to_activate.push(cube);
            }

            for fluff in fluff.iter().cloned() {
                space.fluff_notifier.notify(super::SpaceFluff {
                    position: cube,
                    fluff,
                });
            }
        }

        self.behaviors
            .commit(&mut space.behaviors, check, &mut no_outputs)
            .map_err(|e| e.context("behaviors".into()))?;

        if !to_activate.is_empty() {
            'b: for query_item in space.behaviors.query::<ActivatableRegion>() {
                // TODO: error return from the function? error report for nonexistence?
                for cube in to_activate.iter().copied() {
                    // TODO: this should be part of the query instead, to allow efficient search
                    if query_item.attachment.bounds.contains_cube(cube) {
                        query_item.behavior.activate();
                        continue 'b;
                    }
                }
            }
        }

        Ok(())
    }
}

impl Merge for SpaceTransaction {
    type MergeCheck = <BehaviorSetTransaction<Space> as Merge>::MergeCheck;
    type Conflict = SpaceTransactionConflict;

    fn check_merge(&self, other: &Self) -> Result<Self::MergeCheck, Self::Conflict> {
        let mut cubes1 = &self.cubes;
        let mut cubes2 = &other.cubes;
        if cubes1.len() > cubes2.len() {
            // The cost of the check is the cost of iterating over keys, so iterate over
            // the smaller map rather than the larger.
            // TODO: We can improve further by taking advantage of sortedness, using the
            // first and last of one set to iterate over a range of the other.
            // alloc::collections::btree_set::Intersection implements something like this,
            // but unfortunately, does not have an analogue for BTreeMap.
            mem::swap(&mut cubes1, &mut cubes2);
        }
        for (&cube, t1) in cubes1 {
            if let Some(t2) = cubes2.get(&cube) {
                let CubeMergeCheck {} =
                    t1.check_merge(t2)
                        .map_err(|conflict| SpaceTransactionConflict::Cube {
                            cube: cube.into(),
                            conflict,
                        })?;
            }
        }
        self.behaviors
            .check_merge(&other.behaviors)
            .map_err(SpaceTransactionConflict::Behaviors)
    }

    fn commit_merge(&mut self, mut other: Self, check: Self::MergeCheck) {
        let Self { cubes, behaviors } = self;

        if other.cubes.len() > cubes.len() {
            // Whichever cube set is shorter, iterate that one
            mem::swap(cubes, &mut other.cubes);
        }
        for (cube, t2) in other.cubes {
            match cubes.entry(cube) {
                Occupied(mut entry) => {
                    entry.get_mut().commit_merge(t2, CubeMergeCheck {});
                }
                Vacant(entry) => {
                    entry.insert(t2);
                }
            }
        }

        behaviors.commit_merge(other.behaviors, check);
    }
}

impl fmt::Debug for SpaceTransaction {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        let Self { cubes, behaviors } = self;
        let mut ds = fmt.debug_struct("SpaceTransaction");
        for (cube, txn) in cubes {
            ds.field(&Cube::from(*cube).refmt(&ConciseDebug).to_string(), txn);
        }
        if !behaviors.is_empty() {
            ds.field("behaviors", &behaviors);
        }
        ds.finish()
    }
}

/// Transaction precondition error type for a [`SpaceTransaction`].
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum SpaceTransactionMismatch {
    #[allow(missing_docs)]
    Cube(Cube),

    /// The transaction tried to modify something outside of the space bounds.
    OutOfBounds {
        /// Bounds within which the transaction attempted to make a change.
        /// (This is not necessarily equal to [`SpaceTransaction::bounds()`])
        transaction: GridAab,

        /// Bounds of the space.
        space: GridAab,
    },

    #[allow(missing_docs)]
    Behaviors(behavior::BehaviorTransactionMismatch),
}

/// Transaction conflict error type for a [`SpaceTransaction`].
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum SpaceTransactionConflict {
    #[allow(missing_docs)]
    Cube {
        cube: Cube, // TODO: GridAab instead?
        conflict: CubeConflict,
    },
    #[allow(missing_docs)]
    Behaviors(behavior::BehaviorTransactionConflict),
}

crate::util::cfg_should_impl_error! {
    impl std::error::Error for SpaceTransactionMismatch {
        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
            match self {
                SpaceTransactionMismatch::Cube(_) => None,
                SpaceTransactionMismatch::OutOfBounds {.. } => None,
                SpaceTransactionMismatch::Behaviors(mismatch) => Some(mismatch),
            }
        }
    }
    impl std::error::Error for SpaceTransactionConflict {
        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
            match self {
                SpaceTransactionConflict::Cube { conflict, .. } => Some(conflict),
                SpaceTransactionConflict::Behaviors(conflict) => Some(conflict),
            }
        }
    }
}

impl fmt::Display for SpaceTransactionMismatch {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            SpaceTransactionMismatch::Cube(cube) => {
                write!(f, "mismatch at cube {c}", c = cube.refmt(&ConciseDebug))
            }

            SpaceTransactionMismatch::OutOfBounds { transaction, space } => {
                // TODO: don't use Debug formatting here — we'll need to decide what Display formatting for an AAB is
                write!(
                    f,
                    "transaction bounds {transaction:?} exceed space bounds {space:?}"
                )
            }
            SpaceTransactionMismatch::Behaviors(_) => write!(f, "in behaviors"),
        }
    }
}
impl fmt::Display for SpaceTransactionConflict {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            SpaceTransactionConflict::Cube { cube, conflict: _ } => {
                write!(f, "conflict at cube {c}", c = cube.refmt(&ConciseDebug))
            }
            SpaceTransactionConflict::Behaviors(_) => write!(f, "conflict in behaviors"),
        }
    }
}

/// A modification to the contents of single cube of a [`Space`].
///
/// To make use of this, insert it into a [`SpaceTransaction`] to specify _which_ cube is
/// modified. This type does not function directly as a [`Transaction`] (though it does
/// implement [`Merge`]).
#[derive(Clone, Default, Eq, PartialEq)]
pub struct CubeTransaction {
    /// Previous block which must occupy this cube.
    /// If `None`, no precondition.
    old: Option<Block>,

    /// Block to be put in this cube.
    /// If `None`, this is only a precondition for modifying another block.
    new: Option<Block>,

    /// If true, two transactions with the same `new` block may not be merged.
    conserved: bool,

    /// The cube was “activated” (clicked on, more or less) and behaviors attached to
    /// that region of space should respond to that.
    activate_behavior: bool,

    /// [`Fluff`] to emit at this location when the transaction is committed.
    ///
    /// TODO: eventually will need rotation and possibly intra-cube positioning.
    ///
    /// TODO: define a merge ordering. should this be a multi-BTreeSet?
    ///
    /// TODO: Allow having a single entry with no allocation?
    fluff: Vec<Fluff>,
}

impl fmt::Debug for CubeTransaction {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let Self {
            old,
            new,
            conserved,
            activate_behavior,
            fluff,
        } = self;
        let mut ds = f.debug_struct("CubeTransaction");
        if old.is_some() || new.is_some() {
            ds.field("old", &old);
            ds.field("new", &new);
            ds.field("conserved", &conserved);
        }
        if *activate_behavior {
            ds.field("activate_behavior", &activate_behavior);
        }
        if !fluff.is_empty() {
            ds.field("fluff", &fluff);
        }
        ds.finish()
    }
}

impl CubeTransaction {
    /// Creates a [`SpaceTransaction`] that applies `self` to the given cube of the space.
    pub fn at(self, cube: Cube) -> SpaceTransaction {
        SpaceTransaction {
            cubes: BTreeMap::from([(<[i32; 3]>::from(cube), self)]),
            ..Default::default()
        }
    }

    pub(crate) const ACTIVATE_BEHAVIOR: Self = Self {
        old: None,
        new: None,
        conserved: false,
        activate_behavior: true,
        fluff: Vec::new(),
    };

    /// Construct a [`CubeTransaction`] that may check and may replace the block in the cube.
    ///
    /// If `old` is not [`None`], requires that the existing block is that block or the
    /// transaction will fail.
    /// If `new` is not [`None`], replaces the existing block with `new`.
    pub fn replacing(old: Option<Block>, new: Option<Block>) -> Self {
        CubeTransaction {
            old,
            new,
            conserved: true,
            ..Default::default()
        }
    }

    /// Sets the block to be placed at this cube, replacing any existing modification instruction
    /// This does not affect a precondition on the existing block, or the conservative option.
    ///
    /// This is thus comparable to the effect of a direct [`Space::set()`] after the rest of the
    /// transaction.
    //---
    // TODO: no tests
    pub fn overwrite(&mut self, block: Block) {
        self.new = Some(block);
    }

    #[doc(hidden)] // TODO: good public API?
    pub fn new_mut(&mut self) -> Option<&mut Block> {
        self.new.as_mut()
    }

    /// Emit [`Fluff`] (sound/particle effects) at this cube when the transaction is committed.
    pub fn fluff(fluff: Fluff) -> Self {
        let mut this = Self::default();
        this.add_fluff(fluff);
        this
    }

    /// Emit [`Fluff`] (sound/particle effects) at this cube when the transaction is committed,
    /// in addition to its other effects.
    pub fn add_fluff(&mut self, fluff: Fluff) {
        self.fluff.push(fluff)
    }
}

impl Merge for CubeTransaction {
    type MergeCheck = CubeMergeCheck;
    type Conflict = CubeConflict;

    fn check_merge(&self, other: &Self) -> Result<Self::MergeCheck, Self::Conflict> {
        let conflict = CubeConflict {
            // Incompatible preconditions will always fail.
            old: matches!((&self.old, &other.old), (Some(a), Some(b)) if a != b),
            new: if self.conserved {
                // Replacing the same cube twice is not allowed -- even if they're
                // equal, doing so could violate an intended conservation law.
                self.new.is_some() && other.new.is_some()
            } else {
                // If nonconservative, then we simply require equal outcomes.
                matches!((&self.new, &other.new), (Some(a), Some(b)) if a != b)
            },
        };

        if (conflict
            != CubeConflict {
                old: false,
                new: false,
            })
        {
            Err(conflict)
        } else {
            Ok(CubeMergeCheck {})
        }
    }

    fn commit_merge(&mut self, other: Self, CubeMergeCheck {}: Self::MergeCheck) {
        let Self {
            old,
            new,
            conserved,
            activate_behavior,
            fluff,
        } = self;

        // This would be more elegant if `conserved` was within the `self.new` Option.
        *conserved = (*conserved && new.is_some()) || (other.conserved && other.new.is_some());

        transaction::merge_option(old, other.old, transaction::panic_if_not_equal);
        transaction::merge_option(new, other.new, transaction::panic_if_not_equal);

        *activate_behavior |= other.activate_behavior;

        fluff.extend(other.fluff);
    }
}

#[doc(hidden)]
#[derive(Debug)]
#[non_exhaustive]
pub struct CubeMergeCheck {
    // This might end up having some data later.
    // For now, it's a placeholder to avoid passing () around
    // and getting clippy::let_unit_value warnings
}

/// Transaction conflict error type for a single [`CubeTransaction`] within a
/// [`SpaceTransaction`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct CubeConflict {
    /// The transactions have conflicting preconditions (`old` blocks).
    pub(crate) old: bool,
    /// The transactions are attempting to modify the same cube.
    pub(crate) new: bool,
}

crate::util::cfg_should_impl_error! {impl std::error::Error for CubeConflict {}}

impl fmt::Display for CubeConflict {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            CubeConflict {
                old: true,
                new: false,
            } => write!(f, "different preconditions"),
            CubeConflict {
                old: false,
                new: true,
            } => write!(f, "cannot write the same cube twice"),
            CubeConflict {
                old: true,
                new: true,
            } => write!(f, "different preconditions (with write)"),
            CubeConflict {
                old: false,
                new: false,
            } => unreachable!(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::behavior::NoopBehavior;
    use crate::block::AIR;
    use crate::content::make_some_blocks;
    use crate::inv::EphemeralOpaque;
    use crate::transaction::TransactionTester;
    use core::sync::atomic::{AtomicU32, Ordering};
    use pretty_assertions::assert_eq;

    #[test]
    fn set_out_of_bounds_conserved_fails() {
        let [block] = make_some_blocks();
        // Note: by using .check() we validate that it doesn't fail in the commit phase
        SpaceTransaction::set_cube([1, 0, 0], None, Some(block))
            .check(&Space::empty_positive(1, 1, 1))
            .unwrap_err();
    }

    #[test]
    fn set_out_of_bounds_nonconserved_succeeds() {
        let [block] = make_some_blocks();
        SpaceTransaction::set_cube([1, 0, 0], None, Some(block))
            .nonconserved()
            .execute(&mut Space::empty_positive(1, 1, 1), &mut no_outputs)
            .unwrap();
    }

    #[test]
    fn compare_out_of_bounds_conserved_fails() {
        let [block] = make_some_blocks();
        SpaceTransaction::set_cube([1, 0, 0], Some(block), None)
            .check(&Space::empty_positive(1, 1, 1))
            .unwrap_err();
    }

    #[test]
    fn compare_out_of_bounds_nonconserved_fails() {
        let [block] = make_some_blocks();
        SpaceTransaction::set_cube([1, 0, 0], Some(block), None)
            .nonconserved()
            .check(&Space::empty_positive(1, 1, 1))
            .unwrap_err();
    }

    #[test]
    fn merge_allows_independent() {
        let [b1, b2, b3] = make_some_blocks();
        let t1 = SpaceTransaction::set_cube([0, 0, 0], Some(b1.clone()), Some(b2.clone()));
        let t2 = SpaceTransaction::set_cube([1, 0, 0], Some(b1.clone()), Some(b3.clone()));
        let t3 = t1.clone().merge(t2.clone()).unwrap();
        assert_eq!(
            t3.cubes.into_iter().collect::<Vec<_>>(),
            vec![
                (
                    [0, 0, 0],
                    CubeTransaction {
                        old: Some(b1.clone()),
                        new: Some(b2.clone()),
                        conserved: true,
                        activate_behavior: false,
                        fluff: vec![],
                    }
                ),
                (
                    [1, 0, 0],
                    CubeTransaction {
                        old: Some(b1.clone()),
                        new: Some(b3.clone()),
                        conserved: true,
                        activate_behavior: false,
                        fluff: vec![],
                    }
                ),
            ]
        );
    }

    #[test]
    fn merge_rejects_same_new_conserved() {
        let [block] = make_some_blocks();
        let t1 = SpaceTransaction::set_cube([0, 0, 0], None, Some(block.clone()));
        let t2 = SpaceTransaction::set_cube([0, 0, 0], None, Some(block.clone()));
        t1.merge(t2).unwrap_err();
    }

    #[test]
    fn merge_allows_same_new_nonconserved() {
        let [old, new] = make_some_blocks();
        let t1 = SpaceTransaction::set_cube([0, 0, 0], Some(old), Some(new.clone())).nonconserved();
        let t2 = SpaceTransaction::set_cube([0, 0, 0], None, Some(new.clone())).nonconserved();
        assert_eq!(t1.clone().merge(t2).unwrap(), t1);
    }

    #[test]
    fn merge_rejects_different_new_conserved() {
        let [b1, b2] = make_some_blocks();
        let t1 = SpaceTransaction::set_cube([0, 0, 0], None, Some(b1.clone()));
        let t2 = SpaceTransaction::set_cube([0, 0, 0], None, Some(b2.clone()));
        t1.merge(t2).unwrap_err();
    }

    #[test]
    fn merge_rejects_different_new_nonconserved() {
        let [b1, b2] = make_some_blocks();
        let t1 = SpaceTransaction::set_cube([0, 0, 0], None, Some(b1.clone())).nonconserved();
        let t2 = SpaceTransaction::set_cube([0, 0, 0], None, Some(b2.clone())).nonconserved();
        t1.merge(t2).unwrap_err();
    }

    #[test]
    fn merge_rejects_different_old() {
        let [b1, b2] = make_some_blocks();
        let t1 = SpaceTransaction::set_cube([0, 0, 0], Some(b1.clone()), None);
        let t2 = SpaceTransaction::set_cube([0, 0, 0], Some(b2.clone()), None);
        t1.merge(t2).unwrap_err();
    }

    #[test]
    fn merge_allows_same_old() {
        let [b1, b2] = make_some_blocks();
        let t1 = SpaceTransaction::set_cube([0, 0, 0], Some(b1.clone()), Some(b2.clone()));
        let t2 = SpaceTransaction::set_cube([0, 0, 0], Some(b1.clone()), None);
        assert_eq!(t1.clone(), t1.clone().merge(t2).unwrap());
    }

    #[test]
    fn activate() {
        let mut space = Space::empty_positive(1, 1, 1);
        let cube = Cube::new(0, 0, 0);

        let signal = Arc::new(AtomicU32::new(0));
        SpaceTransaction::add_behavior(
            GridAab::single_cube(cube),
            ActivatableRegion {
                // TODO: This sure is clunky
                effect: EphemeralOpaque::new(Arc::new({
                    let signal = signal.clone();
                    move || {
                        signal.fetch_add(1, Ordering::Relaxed);
                    }
                })),
            },
        )
        .execute(&mut space, &mut no_outputs)
        .unwrap();

        CubeTransaction::ACTIVATE_BEHAVIOR
            .at(cube)
            .execute(&mut space, &mut drop)
            .unwrap();
        assert_eq!(signal.load(Ordering::Relaxed), 1);
    }

    #[test]
    fn systematic() {
        let [b1, b2, b3] = make_some_blocks();
        TransactionTester::new()
            .transaction(SpaceTransaction::default(), |_, _| Ok(()))
            .transaction(
                SpaceTransaction::set_cube([0, 0, 0], Some(b1.clone()), Some(b2.clone())),
                |_, after| {
                    if after[[0, 0, 0]] != b2 {
                        return Err("did not set b2".into());
                    }
                    Ok(())
                },
            )
            .transaction(
                SpaceTransaction::set_cube([0, 0, 0], Some(b1.clone()), Some(b3.clone())),
                |_, after| {
                    if after[[0, 0, 0]] != b3 {
                        return Err("did not set b3".into());
                    }
                    Ok(())
                },
            )
            .transaction(
                SpaceTransaction::set_cube([0, 0, 0], None, Some(b2.clone())),
                |_, after| {
                    if after[[0, 0, 0]] != b2 {
                        return Err("did not set b2".into());
                    }
                    Ok(())
                },
            )
            .transaction(
                SpaceTransaction::set_cube([0, 0, 0], Some(b2.clone()), None),
                |_, _| Ok(()),
            )
            .transaction(
                SpaceTransaction::set_cube([0, 0, 0], Some(b1.clone()), None),
                |_, _| Ok(()),
            )
            .transaction(
                CubeTransaction::ACTIVATE_BEHAVIOR.at(Cube::new(0, 0, 0)),
                // TODO: Add a test that activation happened once that's possible
                |_, _| Ok(()),
            )
            .transaction(
                CubeTransaction::ACTIVATE_BEHAVIOR.at(Cube::new(1, 0, 0)),
                // TODO: Add a test that activation happened once that's possible
                |_, _| Ok(()),
            )
            .target(|| Space::empty_positive(2, 1, 1))
            .target(|| {
                let mut space = Space::empty_positive(2, 1, 1);
                space.set([0, 0, 0], &b1).unwrap();
                space
            })
            .target(|| {
                let mut space = Space::empty_positive(2, 1, 1);
                space.set([0, 0, 0], &b2).unwrap();
                space
            })
            .target(|| {
                // This space makes the test transactions at [0, 0, 0] out of bounds
                Space::empty(GridAab::from_lower_size([1, 0, 0], [1, 1, 1]))
            })
            // TODO: more spaces
            .test();
    }

    #[test]
    fn bounds_empty() {
        assert_eq!(SpaceTransaction::default().bounds(), None);
    }

    #[test]
    fn bounds_single_cube() {
        assert_eq!(
            SpaceTransaction::set_cube([-7, 3, 5], None, Some(AIR)).bounds(),
            Some(GridAab::single_cube(Cube::new(-7, 3, 5)))
        );
    }

    #[test]
    fn bounds_multi_cube() {
        let t1 = SpaceTransaction::set_cube([-7, 3, 5], None, Some(AIR));
        let t2 = SpaceTransaction::set_cube([10, 3, 5], None, Some(AIR));
        assert_eq!(
            t1.merge(t2).unwrap().bounds(),
            Some(GridAab::from_lower_upper([-7, 3, 5], [11, 4, 6]))
        );
    }

    #[test]
    fn bounds_behavior() {
        let bounds = GridAab::from_lower_size([1, 2, 3], [4, 5, 6]);
        let txn = SpaceTransaction::add_behavior(bounds, NoopBehavior(1));
        assert_eq!(txn.bounds(), Some(bounds));
    }
}