grid-engine 0.1.2

A flexible and efficient library for managing 2D grid-based layouts with automatic collision handling and dynamic vertical expansion
Documentation
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
// Copyright (c) 2025 Thiago Ramos
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

//! Grid Engine manages a 2D grid system with support for adding, removing, and moving items.
//!
//! # Key Features
//!
//! - Automatic collision detection and handling
//! - Event system for tracking changes
//! - Expanding the grid on the y axis dynamically
//!
//! # Example
//!
//! ```
//! use grid_engine::grid_engine::GridEngine;
//! # use std::error::Error;
//!
//! # fn main() -> Result<(), Box<dyn Error>> {
//! let mut grid = GridEngine::new(10, 12);
//!
//! // Add items to the grid
//! grid.add_item("item1".to_string(), 2, 2, 2, 4)?;
//!
//! // Move items (handles collisions automatically)
//! grid.move_item("item1", 4, 4)?;
//!
//! // Remove items
//! grid.remove_item("item1")?;
//! #
//! # Ok(())
//! # }
//! ```

use crate::error::{GridEngineError, InnerGridError, ItemError};
use crate::grid_events::{ChangesEventValue, GridEvents};
use crate::inner_grid::{InnerGrid, UpdateGridOperation};
use crate::node::Node;
use crate::utils::{ForCellArgs, for_cell};
use std::{collections::BTreeMap, fmt::Debug};

/// Represents data for an item addition change
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct AddChangeData {
    /// The node being added to the grid
    value: Node,
}

impl AddChangeData {
    /// Creates a new AddChangeData instance
    ///
    /// # Arguments
    ///
    /// * `value` - The node being added to the grid
    ///
    /// # Returns
    ///
    /// A new instance of AddChangeData
    pub fn new(value: Node) -> Self {
        Self { value }
    }

    /// Returns the node being added
    pub fn value(&self) -> &Node {
        &self.value
    }
}

/// Represents data for an item removal change
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct RemoveChangeData {
    /// The node being removed from the grid
    value: Node,
}

impl RemoveChangeData {
    /// Creates a new RemoveChangeData instance
    ///
    /// # Arguments
    ///
    /// * `value` - The node being removed from the grid
    ///
    /// # Returns
    ///
    /// A new instance of RemoveChangeData
    pub fn new(value: Node) -> Self {
        Self { value }
    }

    /// Returns the node being removed
    pub fn value(&self) -> &Node {
        &self.value
    }
}

/// Represents data for an item movement change
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct MoveChangeData {
    /// The original state of the node
    old_value: Node,
    /// The new state of the node after movement
    new_value: Node,
}

impl MoveChangeData {
    /// Creates a new MoveChangeData instance
    ///
    /// # Arguments
    ///
    /// * `old_value` - The original state of the node
    /// * `new_value` - The new state of the node after movement
    ///
    /// # Returns
    ///
    /// A new instance of MoveChangeData
    pub fn new(old_value: Node, new_value: Node) -> Self {
        Self {
            old_value,
            new_value,
        }
    }

    /// Returns the original state of the node
    pub fn old_value(&self) -> &Node {
        &self.old_value
    }

    /// Returns the new state of the node after movement
    pub fn new_value(&self) -> &Node {
        &self.new_value
    }
}

/// Represents different types of changes that can occur in the grid
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub enum Change {
    /// Adding a new item to the grid
    Add(AddChangeData),
    /// Removing an existing item from the grid
    Remove(RemoveChangeData),
    /// Moving an item to a new position
    Move(MoveChangeData),
}

/// The main engine for managing a 2D grid system.
///
/// `GridEngine` provides functionality for:
/// - Adding items to specific grid positions
/// - Moving items while handling collisions
/// - Removing items from the grid
/// - Tracking changes through an event system
/// - Expand the grid dynamically on the y axis
///
/// When items collide during placement or movement, the engine automatically
/// repositions affected items to prevent overlapping, the default is to move the collided items down, increasing their y axis.
#[derive(Debug)]
pub struct GridEngine {
    /// The underlying grid structure
    grid: InnerGrid,
    /// Map of item IDs to their Node representations
    items: BTreeMap<String, Node>,
    /// Changes waiting to be applied
    pending_changes: Vec<Change>,
    /// Event system for tracking grid changes
    events: GridEvents,
}

impl GridEngine {
    /// Creates a new GridEngine with specified dimensions.
    ///
    /// # Arguments
    ///
    /// * `rows` - Initial number of rows in the grid
    /// * `cols` - Initial number of columns in the grid
    ///
    /// # Example
    ///
    /// ```
    /// use grid_engine::grid_engine::GridEngine;
    ///
    /// let grid = GridEngine::new(10, 10); // Creates a 10x10 grid
    /// ```
    pub fn new(rows: usize, cols: usize) -> GridEngine {
        GridEngine {
            grid: InnerGrid::new(rows, cols),
            items: BTreeMap::new(),
            pending_changes: Vec::new(),
            events: GridEvents::default(),
        }
    }

    /// Creates a new node with the specified parameters.
    fn new_node(&mut self, id: impl Into<String>, x: usize, y: usize, w: usize, h: usize) -> Node {
        Node::new(id.into(), x, y, w, h)
    }

    /// Creates a change operation to add a new node to the grid.
    fn create_add_change(&mut self, node: Node) {
        self.pending_changes
            .push(Change::Add(AddChangeData { value: node }));
    }

    /// Get the node sorted by id
    ///
    /// # Example
    ///
    /// ```
    /// use grid_engine::grid_engine::GridEngine;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut grid = GridEngine::new(10, 10);
    /// grid.add_item("b".to_string(), 0, 0, 2, 2).unwrap();
    /// grid.add_item("a".to_string(), 0, 2, 2, 2).unwrap();
    ///
    /// let nodes = grid.get_nodes();
    /// assert_eq!(nodes.len(), 2);
    /// assert_eq!(nodes[0].id(), "a");
    /// assert_eq!(nodes[1].id(), "b");
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_nodes(&self) -> Vec<&Node> {
        let mut cloned: Vec<&Node> = self.items.values().collect();
        // Would be better to sort by some created_at
        cloned.sort_by_key(|n| n.id.clone());
        cloned
    }

    /// Gets a reference to the underlying grid structure.
    ///
    /// This provides access to the raw grid data for inspection purposes.
    /// Note that modifications should be made through GridEngine's public methods
    /// rather than directly manipulating the inner grid.
    ///
    /// # Returns
    ///
    /// A reference to the InnerGrid instance
    ///
    /// # Example
    ///
    /// ```
    /// use grid_engine::grid_engine::GridEngine;
    /// use std::error::Error;
    ///
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// let grid = GridEngine::new(10, 10);
    /// let inner_grid = grid.get_inner_grid();
    /// assert_eq!(inner_grid.rows(), 10);
    /// assert_eq!(inner_grid.cols(), 10);
    /// # Ok(())
    /// # }
    pub fn get_inner_grid(&self) -> &InnerGrid {
        &self.grid
    }

    /// Adds an item to the grid at the specified position.
    ///
    /// If the new item would collide with existing items, those items are
    /// automatically repositioned to avoid overlap.
    ///
    /// # Arguments
    ///
    /// * `id` - Unique identifier for the item
    /// * `x` - X coordinate (column) for item placement
    /// * `y` - Y coordinate (row) for item placement
    /// * `w` - Width of the item in grid cells
    /// * `h` - Height of the item in grid cells
    ///
    /// # Returns
    ///
    /// * `Ok(&Node)` - Reference to the newly added node
    /// * `Err(GridEngineError)` - If item already exists or placement fails
    ///
    /// # Example
    ///
    /// ```
    /// use grid_engine::grid_engine::GridEngine;
    /// use std::error::Error;
    ///
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// let mut grid = GridEngine::new(10, 10);
    /// grid.add_item("box1".to_string(), 0, 0, 2, 2)?; // 2x2 item at top-left
    ///
    /// // Check if the item was added correctly
    /// let item = grid.get_nodes();
    /// assert_eq!(item.len(), 1);
    /// assert_eq!(item[0].id(), "box1");
    ///
    /// # Ok(())
    /// # }
    /// ```
    pub fn add_item(
        &mut self,
        id: impl Into<String>,
        x: usize,
        y: usize,
        w: usize,
        h: usize,
    ) -> Result<&Node, GridEngineError> {
        let id = id.into();
        if self.items.contains_key(&id) {
            return Err(GridEngineError::Item(ItemError::ItemAlreadyExists { id }));
        };

        let node = self.new_node(id, x, y, w, h);
        let node_id = node.id.to_string();

        self.handle_collision(&node, x, y, &mut self.grid.clone())?;

        self.create_add_change(node);

        self.apply_changes(&self.pending_changes.clone())?;
        self.pending_changes.clear();

        let node = self
            .items
            .get(&node_id)
            .ok_or(InnerGridError::MismatchedGridItem { id: node_id })?;
        Ok(node)
    }

    fn create_remove_change(&mut self, node: &Node) {
        self.pending_changes.push(Change::Remove(RemoveChangeData {
            value: node.clone(),
        }));
    }

    /// Removes an item from the grid by its ID.
    ///
    /// # Arguments
    ///
    /// * `id` - ID of the item to remove
    ///
    /// # Returns
    ///
    /// * `Ok(Node)` - The removed node
    /// * `Err(GridEngineError)` - If item doesn't exist
    ///
    /// # Example
    ///
    /// ```
    /// use grid_engine::grid_engine::GridEngine;
    /// use std::error::Error;
    ///
    /// # fn main() -> Result<(), Box<dyn Error>> {
    ///
    /// let mut grid = GridEngine::new(10, 10);
    /// grid.add_item("box1".to_string(), 0, 0, 2, 2)?;
    /// grid.remove_item("box1")?; // Removes the item
    ///
    /// # Ok(())
    /// # }
    /// ```
    pub fn remove_item(&mut self, id: &str) -> Result<Node, GridEngineError> {
        let node = match self.items.get(id) {
            Some(node) => node,
            None => Err(GridEngineError::Item(ItemError::ItemNotFound {
                id: id.to_string(),
            }))?,
        }
        .clone();

        self.create_remove_change(&node);

        self.apply_changes(&self.pending_changes.clone())?;
        self.pending_changes.clear();
        Ok(node)
    }

    /// Checks if a node would collide with any existing items at the specified position.
    ///
    /// This is used internally to detect potential collisions before making grid changes.
    /// It considers the node's dimensions and any existing items in the target area.
    ///
    /// # Returns
    ///
    /// * `Ok(Vec<&Node>)` - List of nodes that would collide with the given node
    /// * `Err(InnerGridError)` - If position check fails (e.g., out of bounds)
    fn will_collides_with(
        &self,
        node: &Node,
        x: usize,
        y: usize,
        grid: &mut InnerGrid,
    ) -> Result<Vec<&Node>, InnerGridError> {
        let mut collides_with: Vec<&Node> = Vec::new();

        for_cell(
            ForCellArgs {
                x,
                y,
                w: node.w,
                h: node.h,
            },
            &mut |x, y| {
                let cell = grid
                    .get(x, y)
                    .ok_or(InnerGridError::OutOfBoundsAccess { x, y })?;

                match cell {
                    Some(cell_ref) => {
                        if cell_ref != &node.id {
                            let node = self.items.get(cell_ref).ok_or(
                                InnerGridError::MismatchedGridItem {
                                    id: cell_ref.to_string(),
                                },
                            )?;

                            if !collides_with.contains(&node) {
                                collides_with.push(node);
                            }
                        }
                    }
                    None => {
                        // Nothing to collide with
                    }
                }
                Ok(())
            },
        )?;

        Ok(collides_with)
    }

    /// Handles collision resolution when adding or moving items.
    ///
    /// When a collision is detected, this method:
    /// 1. Identifies all affected items
    /// 2. Calculates new positions for colliding items
    /// 3. Creates appropriate move changes to relocate affected items
    ///
    /// The default collision resolution strategy moves affected items downward,
    /// which may trigger dynamic grid expansion in the y-axis.
    fn handle_collision(
        &mut self,
        node: &Node,
        x: usize,
        y: usize,
        grid: &mut InnerGrid,
    ) -> Result<(), InnerGridError> {
        let collides_with = self
            .will_collides_with(node, x, y, grid)?
            .iter()
            .map(|n| (*n).clone())
            .collect::<Vec<Node>>();

        for collided in collides_with {
            let mut new_grid = grid.clone();

            node.update_grid(&mut new_grid, UpdateGridOperation::Remove)?;
            let new_x = collided.x;
            let new_y = y + node.h;
            self.create_move_change(collided, new_x, new_y, &mut new_grid)?;
        }

        Ok(())
    }

    /// Creates a change operation to move a node to a new position.
    ///
    /// This method:
    /// 1. Handles any collisions at the new position
    /// 2. Checks if the node was already scheduled to move
    /// 3. Creates a Move change operation if needed
    ///
    /// # Arguments
    ///
    /// * `node` - The node to move
    /// * `new_x` - Target x coordinate
    /// * `new_y` - Target y coordinate
    /// * `grid` - The grid to check for collisions
    fn create_move_change(
        &mut self,
        node: Node,
        new_x: usize,
        new_y: usize,
        grid: &mut InnerGrid,
    ) -> Result<(), InnerGridError> {
        let old_node = node.clone();
        self.handle_collision(&node, new_x, new_y, grid)?;

        let already_moved = self.pending_changes.iter().any(|change| match change {
            Change::Move(data) => data.new_value.id == node.id,
            _ => false,
        });

        if already_moved {
            return Ok(());
        }

        self.pending_changes.push(Change::Move(MoveChangeData {
            old_value: old_node,
            new_value: Node::new(node.id.to_string(), new_x, new_y, node.w, node.h),
        }));

        Ok(())
    }

    /// Moves an existing item to a new position in the grid.
    ///
    /// If the move would cause collisions, affected items are automatically
    /// repositioned to prevent overlap.
    ///
    /// # Arguments
    ///
    /// * `id` - ID of the item to move
    /// * `new_x` - New X coordinate
    /// * `new_y` - New Y coordinate
    ///
    /// # Returns
    ///
    /// * `Ok(())` - If move successful
    /// * `Err(GridEngineError)` - If item doesn't exist or move invalid
    ///
    /// # Example
    ///
    /// ```
    /// use grid_engine::grid_engine::GridEngine;
    /// # use std::error::Error;
    ///
    /// # fn main() -> Result<(), Box<dyn Error>> {
    ///
    /// let mut grid = GridEngine::new(10, 10);
    /// grid.add_item("box1".to_string(), 0, 0, 2, 2)?;
    /// grid.move_item("box1", 2, 2)?; // Moves box to position 2,2
    ///
    /// // Check if the item was moved correctly
    /// let item = grid.get_nodes();
    /// assert_eq!(item.len(), 1);
    /// assert_eq!(item[0].x(), &2);
    /// assert_eq!(item[0].y(), &2);
    ///
    /// # Ok(())
    /// # }
    ///
    /// ```
    pub fn move_item(
        &mut self,
        id: &str,
        new_x: usize,
        new_y: usize,
    ) -> Result<(), GridEngineError> {
        let node = match self.items.get(id) {
            Some(node) => node,
            None => Err(GridEngineError::Item(ItemError::ItemNotFound {
                id: id.to_string(),
            }))?,
        };

        self.create_move_change(node.clone(), new_x, new_y, &mut self.grid.clone())?;

        self.apply_changes(&self.pending_changes.clone())?;
        self.pending_changes.clear();

        Ok(())
    }

    /// Applies a batch of changes to the grid.
    ///
    /// This method handles the actual application of all pending changes to both
    /// the grid structure and the item tracking system. Changes are applied in order,
    /// and all operations are executed atomically - if any change fails, none of
    /// the changes will be applied.
    ///
    /// After successful application, triggers change events to notify any registered listeners.
    ///
    /// # Arguments
    ///
    /// * `changes` - Vector of changes to apply (Add, Remove, or Move operations)
    ///
    /// # Returns
    ///
    /// * `Ok(())` - If all changes were applied successfully
    /// * `Err(GridEngineError)` - If any change application fails
    /// ```
    fn apply_changes(&mut self, changes: &[Change]) -> Result<(), GridEngineError> {
        for change in changes.iter() {
            match &change {
                Change::Add(data) => {
                    let node = &data.value;

                    node.update_grid(&mut self.grid, UpdateGridOperation::Add)?;

                    self.items.insert(node.id.to_string(), node.clone());
                }
                Change::Remove(data) => {
                    let node = &data.value;

                    node.update_grid(&mut self.grid, UpdateGridOperation::Remove)?;

                    self.items.remove(&node.id);
                }
                Change::Move(data) => {
                    let node = &data.new_value;
                    let old_node = &data.old_value;

                    old_node.update_grid(&mut self.grid, UpdateGridOperation::Remove)?;

                    self.items.insert(node.id.to_string(), node.clone());

                    node.update_grid(&mut self.grid, UpdateGridOperation::Add)?;
                }
            }
        }

        self.events
            .trigger_changes_event(&ChangesEventValue::new(changes.to_vec()));
        Ok(())
    }

    /// Returns a reference to the grid events system.
    pub fn events(&self) -> &GridEvents {
        &self.events
    }

    /// Returns a mutable reference to the grid events system.
    pub fn events_mut(&mut self) -> &mut GridEvents {
        &mut self.events
    }
}

mod tests {
    #[allow(unused_imports)]
    use super::*;

    #[test]
    fn test_for_cell() {
        let mut results = Vec::new();
        let mut callback = |x: usize, y: usize| {
            results.push((x, y));
            Ok(())
        };

        for_cell(
            ForCellArgs {
                x: 1,
                y: 2,
                w: 2,
                h: 2,
            },
            &mut callback,
        )
        .unwrap();

        assert_eq!(results, vec![(1, 2), (1, 3), (2, 2), (2, 3)]);
    }

    #[test]
    fn test_add_item() {
        let mut engine = GridEngine::new(10, 10);
        let item_0_id = engine
            .add_item("0".to_string(), 0, 0, 2, 2)
            .unwrap()
            .id
            .clone();

        assert!(engine.items.len() == 1);
        for_cell(
            ForCellArgs {
                x: 0,
                y: 0,
                w: 2,
                h: 2,
            },
            &mut |x, y| {
                assert_eq!(engine.grid.get(x, y).unwrap().as_ref().unwrap(), &item_0_id);
                Ok(())
            },
        )
        .unwrap();
    }

    #[test]
    fn test_add_item_handle_duplicated_id() {
        let mut engine = GridEngine::new(10, 10);
        engine.add_item("0".to_string(), 0, 0, 2, 2).unwrap();

        assert!(engine.add_item("0".to_string(), 0, 0, 2, 2).is_err())
    }

    #[test]
    fn test_add_item_handle_collision() {
        let mut engine = GridEngine::new(10, 10);
        let item_0_id = engine
            .add_item("0".to_string(), 0, 0, 2, 2)
            .unwrap()
            .id
            .clone();
        let item_1_id = engine
            .add_item("1".to_string(), 0, 0, 2, 2)
            .unwrap()
            .id
            .clone();

        // Item 0 should stay in position 0, 0
        let item_0 = engine.items.get(&item_0_id).unwrap();
        assert_eq!(item_0.x, 0);
        assert_eq!(item_0.y, 2);
        item_0
            .for_cell(&mut |x, y| {
                assert_eq!(engine.grid.get(x, y).unwrap().as_ref().unwrap(), &item_0_id);
                Ok(())
            })
            .unwrap();

        // Item 1 should go to position 0, 2
        let item_1 = engine.items.get(&item_1_id).unwrap();
        assert_eq!(item_1.x, 0);
        assert_eq!(item_1.y, 0);
        item_1
            .for_cell(&mut |x, y| {
                assert_eq!(engine.grid.get(x, y).unwrap().as_ref().unwrap(), &item_1_id);
                Ok(())
            })
            .unwrap();
    }

    #[test]
    fn test_remove_item() {
        let mut engine = GridEngine::new(10, 10);
        let item_0_id = engine
            .add_item("0".to_string(), 0, 0, 2, 3)
            .unwrap()
            .id
            .clone();
        engine.remove_item(&item_0_id).unwrap();
        for_cell(
            ForCellArgs {
                x: 0,
                y: 0,
                w: 2,
                h: 3,
            },
            &mut |x, y| {
                let value = engine.grid.get(x, y).unwrap();
                assert_eq!(value, &None);
                Ok(())
            },
        )
        .unwrap();
    }

    #[test]
    fn test_move_item() {
        let mut engine = GridEngine::new(10, 10);
        let item_0_id = engine
            .add_item("0".to_string(), 0, 0, 2, 2)
            .unwrap()
            .id
            .clone();
        engine.move_item(&item_0_id, 1, 1).unwrap();

        // Asserts that its present on the new position
        for_cell(
            ForCellArgs {
                x: 1,
                y: 1,
                w: 2,
                h: 2,
            },
            &mut |x, y| {
                let item_on_expected_position = engine.grid.get(x, y).unwrap().as_ref().unwrap();
                assert_eq!(item_on_expected_position, &item_0_id);
                Ok(())
            },
        )
        .unwrap();

        // Asserts that its not present on the old position
        for_cell(
            ForCellArgs {
                x: 0,
                y: 0,
                w: 1,
                h: 1,
            },
            &mut |x, y| {
                assert_eq!(engine.grid.get(x, y).unwrap(), &None);
                Ok(())
            },
        )
        .unwrap();
    }

    #[test]
    fn test_move_item_handle_collision() {
        let mut engine = GridEngine::new(10, 10);
        let item_0_id = engine
            .add_item("0".to_string(), 0, 0, 2, 2)
            .unwrap()
            .id
            .clone();
        let item_1_id = engine
            .add_item("1".to_string(), 0, 2, 2, 2)
            .unwrap()
            .id
            .clone();
        engine.move_item("0", 0, 1).unwrap();

        // Item 0 should go to position 0, 1
        let item_0 = engine.items.get(&item_0_id).unwrap();
        assert_eq!(item_0.x, 0);
        assert_eq!(item_0.y, 1);
        item_0
            .for_cell(&mut |x, y| {
                assert_eq!(engine.grid.get(x, y).unwrap().as_ref().unwrap(), &item_0_id);
                Ok(())
            })
            .unwrap();

        // Item 1 should go to position 0, 3
        let item_1 = engine.items.get(&item_1_id).unwrap();
        assert_eq!(item_1.x, 0);
        assert_eq!(item_1.y, 3);
        item_1
            .for_cell(&mut |x, y| {
                assert_eq!(engine.grid.get(x, y).unwrap().as_ref().unwrap(), &item_1_id);
                Ok(())
            })
            .unwrap();
    }

    #[test]
    fn test_will_collides_with() {
        let mut engine = GridEngine::new(10, 10);
        let item_0_id = engine
            .add_item("0".to_string(), 0, 0, 1, 2)
            .unwrap()
            .id
            .clone();

        // Asserts that does not collide with self
        assert!(
            engine
                .will_collides_with(
                    engine.items.get(&item_0_id).unwrap(),
                    0,
                    0,
                    &mut engine.grid.clone()
                )
                .unwrap()
                .is_empty()
        );

        // Asserts that does not collide with empty position
        assert!(
            engine
                .will_collides_with(
                    engine.items.get(&item_0_id).unwrap(),
                    2,
                    2,
                    &mut engine.grid.clone()
                )
                .unwrap()
                .is_empty()
        );

        // Asserts that collide with occupied position
        engine.add_item("1".to_string(), 1, 2, 1, 2).unwrap();

        // Full collision
        assert!(
            engine
                .will_collides_with(
                    engine.items.get(&item_0_id).unwrap(),
                    1,
                    2,
                    &mut engine.grid.clone()
                )
                .unwrap()
                .len()
                == 1
        );

        // Partial collision
        assert!(
            engine
                .will_collides_with(
                    engine.items.get(&item_0_id).unwrap(),
                    1,
                    1,
                    &mut engine.grid.clone()
                )
                .unwrap()
                .len()
                == 1
        );
    }

    #[test]
    fn test_get_nodes() {
        let mut engine = GridEngine::new(10, 10);
        let item_0_id = engine
            .add_item("0".to_string(), 0, 0, 2, 2)
            .unwrap()
            .id
            .clone();
        let item_1_id = engine
            .add_item("1".to_string(), 0, 2, 2, 2)
            .unwrap()
            .id
            .clone();

        let nodes = engine.get_nodes();
        assert_eq!(nodes.len(), 2);
        assert_eq!(nodes[0].id, item_0_id);
        assert_eq!(nodes[1].id, item_1_id);
    }

    #[test]
    fn test_move_result_will_not_collides_with_moving_item() {
        let mut engine = GridEngine::new(10, 10);
        engine.add_item("0".to_string(), 0, 0, 2, 3).unwrap();
        engine.add_item("1".to_string(), 0, 6, 2, 2).unwrap();
        engine.move_item("1", 0, 2).unwrap();

        for_cell(
            ForCellArgs {
                x: 0,
                y: 7,
                w: 2,
                h: 2,
            },
            &mut |x, y| {
                let value = engine.grid.get(x, y).unwrap();
                println!("value: {:?}", value);
                assert_ne!(value, &Some("1".to_string()));
                Ok(())
            },
        )
        .unwrap();
    }

    #[test]
    fn test_node_movements_that_collides_twice_works() {
        let mut engine = GridEngine::new(14, 10);
        engine.add_item("0".to_string(), 1, 1, 2, 3).unwrap();
        engine.add_item("1".to_string(), 2, 4, 2, 4).unwrap();
        engine.add_item("2".to_string(), 0, 6, 2, 4).unwrap();
        engine.move_item("2", 1, 2).unwrap();

        println!("Items: {:#?}", engine.items);

        engine.items.iter().for_each(|(_, node)| {
            node.for_cell(&mut |x, y| {
                let value = engine.grid.get(x, y).unwrap();
                println!("Validating x: {}, y: {}", x, y);
                assert_eq!(&Some(node.clone().id), value);
                Ok(())
            })
            .unwrap();
        });
    }
}