maze_wasm/
wasm_bindgen.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
use crate::wasm_common::{
    new_maze, to_cell_type_enum, MazeWasm, MazeCellTypeWasm,
};
use data_model::MazePoint;
use js_sys::{Array, Object, Reflect};
use maze::{MazeSolution, MazeSolver};
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsValue;

/// Converts a Rust Point to a JavaScript object
fn to_js_point_obj(point: &MazePoint) -> Object {
    let obj = Object::new();
    Reflect::set(
        &obj,
        &JsValue::from_str("row"),
        &JsValue::from_f64(point.row as f64),
    )
    .unwrap();
    Reflect::set(
        &obj,
        &JsValue::from_str("col"),
        &JsValue::from_f64(point.col as f64),
    )
    .unwrap();
    obj
}

/// Converts a cell type to a JavaScript object
fn to_js_cell_info_obj(cell_type: char) -> Object {
    let obj = Object::new();
    Reflect::set(
        &obj,
        &JsValue::from_str("cell_type"),
        &JsValue::from(to_cell_type_enum(cell_type) as u32),
    )
    .unwrap();
    obj
}

#[wasm_bindgen]
/// Web assembly representation of a maze solution
pub struct MazeSolutionWasm {
    //#[cfg_attr(feature = "wasm-bindgen", wasm_bindgen(skip))] - does not work
    #[wasm_bindgen(skip)]
    pub solution: MazeSolution,
}


#[wasm_bindgen]
impl MazeSolutionWasm {
    /// Returns the array of points (if any) associated with the maze solution
    ///
    /// # Returns
    ///
    /// This function will return an array of Javascript objects defining each point in
    /// the solution. Each solution point object has the folllowing properties:
    ///
    /// - `row` - zero-based row index for the solution point
    /// - `col` - zero-based column index for the solution point
    ///
    /// # Examples
    ///
    /// Initialize a maze from a JSON string, then attempt to solve it and, if successful,
    /// print the maze solution path's points
    ///
    /// ```javascript
    /// // Javascript <script> content:
    ///
    /// import init, { MazeWasm } from 'maze_wasm.js';
    ///
    /// async function run() {
    ///     await init();
    ///
    ///     try {
    ///         let maze = new MazeWasm();
    ///         maze.from_json(`{
    ///             \"id\":\"maze_id\",
    ///             \"name\":\"test\",
    ///             \"definition\": {
    ///                 \"grid\":[
    ///                     [\"S\", \"W\", \" \", \" \", \"W\"],
    ///                     [\" \", \"W\", \" \", \"W\", \" \"],
    ///                     [\" \", \" \", \" \", \"W\", \"F\"],
    ///                     [\"W\", \" \", \"W\", \" \", \" \"],
    ///                     [\" \", \" \", \" \", \"W\", \" \"],
    ///                     [\"W\", \"W\", \" \", \" \", \" \"],
    ///                     [\"W\", \"W\", \" \", \"W\", \" \"]
    ///                 ]
    ///         }}`);
    ///         let solution = maze.solve();
    ///         let solutionPoints = solution.get_path_points();
    ///         console.log("Successfully solved maze. Solution points are: ", solutionPoints);
    ///     } catch (e) {
    ///         console.error("Operation failed: ", e);
    ///     }
    /// }
    /// run();
    /// ```
    pub fn get_path_points(&self) -> Array {
        let path_points = Array::new();
        for point in &self.solution.path.points {
            path_points.push(&to_js_point_obj(point));
        }
        path_points
    }
}

#[cfg_attr(feature = "wasm-bindgen", wasm_bindgen)]
impl MazeWasm {
    #[wasm_bindgen(constructor)]
    /// Creates a new maze instance
    ///
    /// # Returns
    ///
    /// A new maze instance
    ///
    /// # Examples
    ///
    /// Create a new maze and print its dimensions (which will be 0 rows x 0 columns)
    ///
    /// ```javascript
    /// // Javascript <script> content:
    ///
    /// import init, { MazeWasm } from 'maze_wasm.js';
    ///
    /// async function run() {
    ///     await init();
    ///
    ///     import init, { MazeWasm } from 'maze_wasm.js';
    ///         ///     try {
    ///         let maze = new MazeWasm();
    ///         console.log("Successfully created maze. Dimensions: ", maze.get_row_count(), "row(s) x ", maze.get_col_count(), " column(s)");
    ///     } catch (e) {
    ///         console.error("Operation failed: ", e);
    ///     }
    /// }
    /// run();
    /// ```
    pub fn new() -> Result<MazeWasm, JsValue> {
        Ok(MazeWasm { maze: new_maze() })
    }
    #[wasm_bindgen]
    /// Resets the maze instance to empty
    ///
    /// # Returns
    ///
    /// The empty maze instance
    ///
    /// # Examples
    ///
    /// Create a new maze, resize it to 10 rows x 5 columns and print out its dimensions.
    /// Then, reset it and print out its dimensions again (which will now be 0 rows x 0 columns).
    ///
    /// ```javascript
    /// // Javascript <script> content:
    ///
    /// import init, { MazeWasm } from 'maze_wasm.js';
    ///
    /// async function run() {
    ///     await init();
    ///
    ///     try {
    ///         let maze = new MazeWasm();
    ///         maze.resize(10, 5);
    ///         console.log("After resize(), dimensions are: ", maze.get_row_count(), "row(s) x ", maze.get_col_count(), " column(s)");
    ///         maze.reset();
    ///         console.log("After reset(), dimensions are: ", maze.get_row_count(), "row(s) x ", maze.get_col_count(), " column(s)");
    ///     } catch (e) {
    ///         console.error("Operation failed: ", e);
    ///     }
    /// }
    /// run();
    /// ```
    pub fn reset(&mut self) -> MazeWasm {
        self.maze.reset();
        self.clone()
    }
    #[wasm_bindgen]
    /// Resizes the maze instance
    ///
    /// # Arguments
    /// * `new_row_count` - New number of rows
    /// * `new_col_count` - New number of columns
    ///
    /// # Returns
    ///
    /// This function will return an error if the maze could not be resized
    ///
    /// # Examples
    ///
    /// Create a new maze, print its dimensions, resize it to 10 rows x 5 columns and
    /// then print out its dimensions again.
    ///
    /// ```javascript
    /// // Javascript <script> content:
    ///
    /// import init, { MazeWasm } from 'maze_wasm.js';
    ///
    /// async function run() {
    ///     await init();
    ///
    ///     try {
    ///         let maze = new MazeWasm ();
    ///         console.log("After creation, dimensions are: ", maze.get_row_count(), "row(s) x ", maze.get_col_count(), " column(s   )");
    ///         maze.resize(10, 5);
    ///         console.log("After resize(), dimensions are: ", maze.get_row_count(), "row(s) x ", maze.get_col_count(), " column(s)");
    ///     } catch (e) {
    ///         console.error("Operation failed: ", e);
    ///     }
    /// }
    /// run();
    pub fn resize(
        &mut self,
        new_row_count: JsValue,
        new_col_count: JsValue,
    ) -> Result<(), JsValue> {
        let new_row_count = Self::arg_to_usize("new_row_count", new_row_count)?;
        let new_col_count = Self::arg_to_usize("new_col_count", new_col_count)?;
        self.maze.definition.resize(new_row_count, new_col_count);
        Ok(())
    }
    #[wasm_bindgen]
    /// Inserts one or more empty rows into the maze instance
    ///
    /// # Arguments
    ///
    /// * `start_row` - Start row index (zero-based)
    /// * `count` - Number of rows to insert
    ///
    /// # Returns
    ///
    /// This function will return an error in the following situations:
    /// - If the target rows are out of range
    ///
    ///  # Examples
    ///
    /// Create a new maze, print its dimensions, insert 5 rows and
    /// then print out its dimensions again (which will now be 5 rows x 0 columns).
    ///
    /// ```javascript
    /// // Javascript <script> content:
    ///
    /// import init, { MazeWasm } from 'maze_wasm.js';
    ///
    /// async function run() {
    ///     await init();
    ///
    ///     try {
    ///         let maze = new MazeWasm();
    ///         console.log("After creation, dimensions are: ", maze.get_row_count(), "row(s) x ", maze.get_col_count(), " column(s)");
    ///         maze.insert_rows(0, 5);
    ///         console.log("After insert_rows(), dimensions are: ", maze.get_row_count(), "row(s) x ", maze.get_col_count(), " column(s)");
    ///     } catch (e) {
    ///         console.error("Operation failed: ", e);
    ///     }
    /// }
    /// run();
    /// ```
    pub fn insert_rows(&mut self, start_row: JsValue, count: JsValue) -> Result<(), JsValue> {
        let start_row = Self::arg_to_usize("start_row", start_row)?;
        let count = Self::arg_to_usize("count", count)?;
        self.maze
            .definition
            .insert_rows(start_row, count)
            .map_err(|e| JsValue::from_str(&e.to_string()))?;
        Ok(())
    }
    #[wasm_bindgen]
    /// Deletes one or more consecutive rows from the maze instance
    ///
    /// # Arguments
    ///
    /// * `start_row` - Start row index (zero-based)
    /// * `count` - Number of rows to delete
    ///
    /// # Returns
    ///
    /// This function will return an error in the following situations:
    /// - If the definition is empty
    /// - If the target rows are out of range
    ///
    ///  # Examples
    ///
    /// Create a new maze, insert 5 rows and print out its dimensions.
    /// Then, delete rows 2 to 4 and print out the dimensions again (which will now be 2 rows x 0 columns).
    ///
    /// ```javascript
    /// // Javascript <script> content:
    ///
    /// import init, { MazeWasm } from 'maze_wasm.js';
    ///
    /// async function run() {
    ///     await init();
    ///
    ///     try {
    ///         let maze = new MazeWasm();
    ///         console.log("After creation, dimensions are: ", maze.get_row_count(), "row(s) x ", maze.get_col_count(), " column(s)");
    ///         maze.insert_rows(0, 5);
    ///         console.log("After insert_rows(), dimensions are: ", maze.get_row_count(), "row(s) x ", maze.get_col_count(), " column(s)");
    ///         maze.delete_rows(1, 3);
    ///         console.log("After delete_rows(), dimensions are: ", maze.get_row_count(), "row(s) x ", maze.get_col_count(), " column(s)");
    ///     } catch (e) {
    ///         console.error("Operation failed: ", e);
    ///     }
    /// }
    /// run();
    /// ```
    pub fn delete_rows(&mut self, start_row: JsValue, count: JsValue) -> Result<(), JsValue> {
        let start_row = Self::arg_to_usize("start_row", start_row)?;
        let count = Self::arg_to_usize("count", count)?;
        self.maze
            .definition
            .delete_rows(start_row, count)
            .map_err(|e| JsValue::from_str(&e.to_string()))?;
        Ok(())
    }
    #[wasm_bindgen]
    /// Inserts one or more empty columns into the maze instance
    ///
    /// # Arguments
    ///
    /// * `start_col` - Start column index (zero-based)
    /// * `count` - Number of columns to insert
    ///
    /// # Returns
    ///
    /// This function will return an error in the following situations:
    /// - If the definition is empty
    /// - If the target columns are out of range
    ///
    /// # Examples
    ///
    /// Create a new maze, insert 1 row and print out its dimensions. Then, insert 10 colums
    /// and print out the dimensions again (which will now be 1 row x 10 columns).
    ///
    /// ```javascript
    /// // Javascript <script> content:
    ///
    /// import init, { MazeWasm } from 'maze_wasm.js';
    ///
    /// async function run() {
    ///     await init();
    ///
    ///     try {
    ///         let maze = new MazeWasm();
    ///         console.log("After creation, dimensions are: ", maze.get_row_count(), "row(s) x ", maze.get_col_count(), " column(s)");
    ///         maze.insert_rows(0, 1);
    ///         console.log("After insert_rows(), dimensions are: ", maze.get_row_count(), "row(s) x ", maze.get_col_count(), " column(s)");
    ///         maze.insert_cols(0, 10);
    ///         console.log("After insert_cols(), dimensions are: ", maze.get_row_count(), "row(s) x ", maze.get_col_count(), " column(s)");
    ///     } catch (e) {
    ///         console.error("Operation failed: ", e);
    ///     }
    /// }
    /// run();
    /// ```
    pub fn insert_cols(&mut self, start_col: JsValue, count: JsValue) -> Result<(), JsValue> {
        let start_col = Self::arg_to_usize("start_col", start_col)?;
        let count = Self::arg_to_usize("count", count)?;
        self.maze
            .definition
            .insert_cols(start_col, count)
            .map_err(|e| JsValue::from_str(&e.to_string()))?;
        Ok(())
    }
    #[wasm_bindgen]
    /// Deletes one or more consecutive columns from the maze instance
    ///
    /// # Arguments
    ///
    /// * `start_col` - Start column index (zero-based)
    /// * `count` - Number of columns to delete
    ///
    /// # Returns
    ///
    /// This function will return an error in the following situations:
    /// - If the definition is empty
    /// - If the target columns are out of range
    ///
    /// # Examples
    ///
    /// Create a new maze, resize it to 10 rows x 5 column and print out its dimensions. Then, delete
    /// columns 2 to 4 and print out the dimensions again (which will now be 10 rows x 2 columns).
    ///
    /// ```javascript
    /// // Javascript <script> content:
    ///
    /// import init, { MazeWasm } from 'maze_wasm.js';
    ///
    /// async function run() {
    ///     await init();
    ///
    ///     try {
    ///         let maze = new MazeWasm();
    ///         maze.resize(10, 5);
    ///         console.log("After resize(), dimensions are: ", maze.get_row_count(), "row(s) x ", maze.get_col_count(), " column(s)");
    ///         maze.delete_cols(1, 3);
    ///         console.log("After delete_cols(), dimensions are: ", maze.get_row_count(), "row(s) x ", maze.get_col_count(), " column(s)");
    ///     } catch (e) {
    ///         console.error("Operation failed: ", e);
    ///     }
    /// }
    /// run();
    /// ```
    pub fn delete_cols(&mut self, start_col: JsValue, count: JsValue) -> Result<(), JsValue> {
        let start_col = Self::arg_to_usize("start_col", start_col)?;
        let count = Self::arg_to_usize("count", count)?;
        self.maze
            .definition
            .delete_cols(start_col, count)
            .map_err(|e| JsValue::from_str(&e.to_string()))?;
        Ok(())
    }
    #[wasm_bindgen]
    /// Checks whether the maze instance is empty
    ///
    /// # Returns
    ///
    /// Boolean
    ///
    /// # Examples
    ///
    /// Create a new maze and print out whether it is empty (`true`). Then, resize it to
    /// 1 row x 2 columns and again print out whether it is empty (`false`).
    ///
    /// ```javascript
    /// // Javascript <script> content:
    ///
    /// import init, { MazeWasm } from 'maze_wasm.js';
    ///
    /// async function run() {
    ///     await init();
    ///
    ///     try {
    ///         let maze = new MazeWasm();
    ///         console.log("After creation, is_empty() = ", maze.is_empty());
    ///         maze.resize(1,2);
    ///         console.log("After resize(), is_empty() = ", maze.is_empty());
    ///     } catch (e) {
    ///         console.error("Operation failed: ", e);
    ///     }
    /// }
    /// run();
    /// ```
    pub fn is_empty(&self) -> bool {
        self.maze.definition.is_empty()
    }
    #[wasm_bindgen]
    /// Returns the number of rows associated with the maze instance
    ///
    /// # Returns
    ///
    /// Number of rows
    ///
    /// # Examples
    ///
    /// Create a new maze and print out the number rows (0). Then, resize it to
    /// 10 rows x 5 columns and then print out the number of rows again (10).
    ///
    /// ```javascript
    /// // Javascript <script> content:
    ///
    /// import init, { MazeWasm } from 'maze_wasm.js';
    ///
    /// async function run() {
    ///     await init();
    ///
    ///     try {
    ///         let maze = new MazeWasm();
    ///         console.log("After creation, get_row_count() = ", maze.get_row_count());
    ///         maze.resize(10, 5);
    ///         console.log("After resize(), get_row_count() = ", maze.get_row_count());
    ///     } catch (e) {
    ///         console.error("Operation failed: ", e);
    ///     }
    /// }
    /// run();
    /// ```
    pub fn get_row_count(&self) -> usize {
        self.maze.definition.row_count()
    }
    #[wasm_bindgen]
    /// Returns the number of columns associated with the maze instance
    ///
    /// # Returns
    ///
    /// Number of columns
    ///
    /// # Examples
    ///
    /// Create a new maze and print out the number columns (0). Then, resize it to
    /// 10 rows x 5 columns and then print out the number of columns again (5).
    ///
    /// ```javascript
    /// // Javascript <script> content:
    ///
    /// import init, { MazeWasm } from 'maze_wasm.js';
    ///
    /// async function run() {
    ///     await init();
    ///
    ///     try {
    ///         let maze = new MazeWasm();
    ///         console.log("After creation, get_col_count() = ", maze.get_col_count());
    ///         maze.resize(10, 5);
    ///         console.log("After resize(), get_col_count() = ", maze.get_col_count());
    ///     } catch (e) {
    ///         console.error("Operation failed: ", e);
    ///     }
    /// }
    /// run();
    /// ```
    pub fn get_col_count(&self) -> usize {
        self.maze.definition.col_count()
    }
    #[wasm_bindgen]
    /// Returns cell information for the given location within the maze instance
    ///
    /// # Arguments
    ///
    /// * `row` - Row index (zero-based)
    /// * `col` - Column index (zero-based)
    ///
    /// # Returns
    ///
    /// This function will return an error in the following situations:
    /// - If the target location is out of range
    ///
    /// If sucessful, a cell information object will be returned with the following properties:
    ///
    /// * `cell_type` - The type ([`MazeCellTypeWasm`]) associated with the cell
    ///
    /// # Examples
    ///
    /// Create a new maze and resize it to 10 rows x 5 columns. Then, print out the cell
    /// information for the cell at row = 1, column = 2.
    ///
    /// ```javascript
    /// // Javascript <script> content:
    ///
    /// import init, { MazeWasm } from 'maze_wasm.js';
    ///
    /// async function run() {
    ///     await init();
    ///
    ///     try {
    ///         let maze = new MazeWasm();
    ///         maze.resize(10, 5);
    ///         console.log("get_cell(1, 2) = ", maze.get_cell(1, 2));
    ///     } catch (e) {
    ///         console.error("Operation failed: ", e);
    ///     }
    /// }
    /// run();
    /// ```
    pub fn get_cell(&self, row: JsValue, col: JsValue) -> Result<Object, JsValue> {
        let row = Self::arg_to_usize("row", row)?;
        if row >= self.maze.definition.row_count() {
            return Err(JsValue::from_str("row out of bounds"));
        }
        let col = Self::arg_to_usize("col", col)?;
        if col >= self.maze.definition.col_count() {
            return Err(JsValue::from_str("column out of bounds"));
        }
        Ok(to_js_cell_info_obj(self.maze.definition.grid[row][col]))
    }
    #[wasm_bindgen]
    /// Sets the start cell location within the maze instance
    ///
    /// # Arguments
    ///
    /// * `start_row` - Start cell row index (zero-based)
    /// * `start_col` - Start cell column index (zero-based)
    ///
    /// # Returns
    ///
    /// This function will return an error in the following situations:
    /// - If the target location is out of range
    ///
    /// # Examples
    ///
    /// Create a new maze, resize it to 10 rows x 5 columns and print out the cell
    /// information for the cell at row = 1, column = 2 (`cell_type` will be [`MazeCellTypeWasm::Empty`]).
    /// Then, set the start cell to that same location and print out the cell information again
    /// (`cell_type` will now be [`MazeCellTypeWasm::Start`]).
    ///
    /// ```javascript
    /// // Javascript <script> content:
    ///
    /// import init, { MazeWasm } from 'maze_wasm.js';
    ///
    /// async function run() {
    ///     await init();
    ///
    ///     try {
    ///         let maze = new MazeWasm();
    ///         maze.resize(10, 5);
    ///         console.log("Before set_start_cell(), get_cell(1, 2) = ", maze.get_cell(1, 2));
    ///         maze.set_start_cell(1, 2);
    ///         console.log("After set_start_cell(), get_cell(1, 2) = ", maze.get_cell(1, 2));
    ///     } catch (e) {
    ///         console.error("Operation failed: ", e);
    ///     }
    /// }
    /// run();
    /// ```
    pub fn set_start_cell(
        &mut self,
        start_row: JsValue,
        start_col: JsValue,
    ) -> Result<(), JsValue> {
        let row = Self::arg_to_usize("start_row", start_row)?;
        let col = Self::arg_to_usize("start_col", start_col)?;
        self.maze
            .definition
            .set_start(Some(MazePoint { row, col }))
            .map_err(|e| JsValue::from_str(&e.to_string()))?;
        Ok(())
    }
    #[wasm_bindgen]
    /// Returns the start cell associated with the maze instance (if any)
    ///
    ///
    /// # Returns
    ///
    /// This function will return an error in the following situations:
    /// - If the start cell does not exist
    ///
    /// If sucessful, an object will be returned with the following properties:
    ///
    /// * `row` - Start cell row index (zero-based)
    /// * `col` - Start cell column index (zero-based)
    ///
    /// # Examples
    ///
    /// Create a new maze, resize it to 10 rows x 5 columns and set the
    /// start cell to be at row = 1, column = 2. Then, retreive and print
    /// out of the details for the start cell.
    ///
    /// ```javascript
    /// // Javascript <script> content:
    ///
    /// import init, { MazeWasm } from 'maze_wasm.js';
    ///
    /// async function run() {
    ///     await init();
    ///
    ///     try {
    ///         let maze = new MazeWasm();
    ///         maze.resize(10, 5);
    ///         maze.set_start_cell(1, 2);
    ///         console.log("get_start_cell() = ", maze.get_start_cell());
    ///     } catch (e) {
    ///         console.error("Operation failed: ", e);
    ///     }
    /// }
    /// run();
    /// ```
    pub fn get_start_cell(&mut self) -> Result<Object, JsValue> {
        if let Some(start) = self.maze.definition.get_start() {
            return Ok(to_js_point_obj(&start));
        }
        Err(JsValue::from_str("no start cell defined"))
    }
    #[wasm_bindgen]
    /// Sets the finish cell location within the maze instance
    ///
    /// # Arguments
    ///
    /// * `finish_row` - Finish cell row index (zero-based)
    /// * `finish_col` - Finish cell column index (zero-based)
    ///
    /// # Returns
    ///
    /// This function will return an error in the following situations:
    /// - If the target location is out of range
    ///
    /// # Examples
    ///
    /// Create a new maze, resize it to 10 rows x 5 columns and print out the cell
    /// information for the cell at row = 3, column = 4 (`cell_type` will be [`MazeCellTypeWasm::Empty`]).
    /// Then, set the finish cell to that same location and print out the cell information again
    /// (`cell_type` will now be [`MazeCellTypeWasm::Finish`]).
    ///
    /// ```javascript
    /// // Javascript <script> content:
    ///
    /// import init, { MazeWasm } from 'maze_wasm.js';
    ///
    /// async function run() {
    ///     await init();
    ///
    ///     try {
    ///         let maze = new MazeWasm();
    ///         maze.resize(10, 5);
    ///         console.log("Before set_finish_cell(), get_cell(3, 4) = ", maze.get_cell(3, 4));
    ///         maze.set_finish_cell(3, 4);
    ///         console.log("After set_finish_cell(), get_cell(3, 4) = ", maze.get_cell(3, 4));
    ///     } catch (e) {
    ///         console.error("Operation failed: ", e);
    ///     }
    /// }
    /// run();
    /// ```
    pub fn set_finish_cell(
        &mut self,
        finish_row: JsValue,
        finish_col: JsValue,
    ) -> Result<(), JsValue> {
        let row = Self::arg_to_usize("finish_row", finish_row)?;
        let col = Self::arg_to_usize("finish_col", finish_col)?;
        self.maze
            .definition
            .set_finish(Some(MazePoint { row, col }))
            .map_err(|e| JsValue::from_str(&e.to_string()))?;
        Ok(())
    }
    #[wasm_bindgen]
    /// Returns the finish cell associated with the maze instance (if any)
    ///
    ///
    /// # Returns
    ///
    /// This function will return an error in the following situations:
    /// - If the finish cell does not exist
    ///
    /// If sucessful, an object will be returned with the following properties:
    ///
    /// * `row` - Finish cell row index (zero-based)
    /// * `col` - Finish cell column index (zero-based)
    ///
    /// # Examples
    ///
    /// Create a new maze, resize it to 10 rows x 5 columns and set the
    /// finish cell to be at row = 9, column = 4. Then, retreive and print
    /// out of the details for the finish cell.
    ///
    /// ```javascript
    /// // Javascript <script> content:
    ///
    /// import init, { MazeWasm } from 'maze_wasm.js';
    ///
    /// async function run() {
    ///     await init();
    ///
    ///     try {
    ///         let maze = new MazeWasm();
    ///         maze.resize(10, 5);
    ///         maze.set_finish_cell(9, 4);
    ///         console.log("get_finish_cell() = ", maze.get_finish_cell());
    ///     } catch (e) {
    ///         console.error("Operation failed: ", e);
    ///     }
    /// }
    /// run();
    /// ```
    pub fn get_finish_cell(&mut self) -> Result<Object, JsValue> {
        if let Some(finish) = self.maze.definition.get_finish() {
            return Ok(to_js_point_obj(&finish));
        }
        Err(JsValue::from_str("no finish cell defined"))
    }
    #[wasm_bindgen]
    /// Sets a range of cells within the maze instance to be walls (`cell_type` = [`MazeCellTypeWasm::Wall`])
    ///
    /// # Arguments
    ///
    /// * `start_row` - Start row index (zero-based)
    /// * `start_col` - Start column index (zero-based)
    /// * `finish_row` - Finish row index (zero-based)
    /// * `finish_col` - Finish column index (zero-based)
    ///
    /// # Returns
    ///
    /// This function will return an error in the following situations:
    /// - If the target location is out of range
    ///
    /// # Examples
    ///
    /// Create a new maze, resize it to 10 rows x 5 columns and then set
    /// cells 2 to 4 to be walls in the first row. Then print the cell
    /// information for the top row, which will have cells (0, 0) and (0, 4)
    /// as  [`MazeCellTypeWasm::Empty`] and cells (0, 1) to (0, 3) as
    /// [`MazeCellTypeWasm::Wall`].
    ///
    /// ```javascript
    /// // Javascript <script> content:
    ///
    /// import init, { MazeWasm } from 'maze_wasm.js';
    ///
    /// async function run() {
    ///     await init();
    ///
    ///     try {
    ///         let maze = new MazeWasm();
    ///         maze.resize(10, 5);
    ///         maze.set_wall_cells(0, 1, 0, 3);
    ///         for (let col  = 0; col < 5; col ++) {
    ///             console.log(`After set_walls_cell(), cell_type at (0, ${col}) = `, maze.get_cell(0, col).cell_type);
    ///         }
    ///     } catch (e) {
    ///         console.error("Operation failed: ", e);
    ///     }
    /// }
    /// run();
    /// ```
    pub fn set_wall_cells(
        &mut self,
        start_row: JsValue,
        start_col: JsValue,
        end_row: JsValue,
        end_col: JsValue,
    ) -> Result<(), JsValue> {
        self.set_cell_values(start_row, start_col, end_row, end_col, 'W')?;
        Ok(())
    }
    #[wasm_bindgen]
    /// Clears a range of cells within the maze instance, setting their `cell_type` = [`MazeCellTypeWasm::Empty`]
    ///
    /// # Arguments
    ///
    /// * `start_row` - Start row index (zero-based)
    /// * `start_col` - Start column index (zero-based)
    /// * `finish_row` - Finish row index (zero-based)
    /// * `finish_col` - Finish column index (zero-based)
    ///
    /// # Returns
    ///
    /// This function will return an error in the following situations:
    /// - If the target location is out of range
    ///
    /// # Examples
    ///
    /// Create a new maze, resize it to 10 rows x 5 columns and then set
    /// cells 2 to 4 to be walls in the first row. Then print the `cell_type`
    /// for the top row, which will have cells (0, 0) and (0, 4)
    /// as [`MazeCellTypeWasm::Empty`] and cells (0, 1) to (0, 3) as
    /// [`MazeCellTypeWasm::Wall`]. Finally, clear cells (0, 2) to (3, 4) and
    /// reprint the `cell_type` for the top row, which will now have
    /// just once cell (0, 1) as [`MazeCellTypeWasm::Wall`].
    ///
    /// ```javascript
    /// // Javascript <script> content:
    ///
    /// import init, { MazeWasm } from 'maze_wasm.js';
    ///
    /// async function run() {
    ///     await init();
    ///
    ///     try {
    ///         let maze = new MazeWasm();
    ///         maze.resize(10, 5);
    ///         maze.set_wall_cells(0, 1, 0, 3);
    ///         for (let col  = 0; col < 5; col ++) {
    ///             console.log(`After set_walls_cell(), cell_type at (0, ${col}) = `, maze.get_cell(0, col).cell_type);
    ///         }
    ///         maze.clear_cells(0, 2, 3, 4);
    ///         for (let col  = 0; col < 5; col ++) {
    ///             console.log(`After clear_walls(), cell_type at (0, ${col}) = `, maze.get_cell(0, col).cell_type);
    ///         }
    ///     } catch (e) {
    ///         console.error("Operation failed: ", e);
    ///     }
    /// }
    /// run();
    /// ```
    pub fn clear_cells(
        &mut self,
        start_row: JsValue,
        start_col: JsValue,
        end_row: JsValue,
        end_col: JsValue,
    ) -> Result<(), JsValue> {
        self.set_cell_values(start_row, start_col, end_row, end_col, ' ')?;
        Ok(())
    }
    #[wasm_bindgen]
    /// This function will return the JSON string representation for the maze instance
    ///
    /// # Returns
    ///
    /// JSON string representing the maze, or an error if the JSON could not be generated
    ///
    ///
    /// # Examples
    ///
    /// Create a new maze, resize it to 6 rows x 5 columns and then set
    /// cells 2 to 4 to be walls in the first 3 rows. The conver to JSON
    /// and print the result.
    ///
    /// ```javascript
    /// // Javascript <script> content:
    ///
    /// import init, { MazeWasm } from 'maze_wasm.js';
    ///
    /// async function run() {
    ///     await init();
    ///
    ///     try {
    ///         let maze = new MazeWasm();
    ///         maze.resize(6, 5);
    ///         maze.set_wall_cells(0, 1, 2, 4);
    ///         let json = maze.to_json();
    ///         console.log("to_json() returned: ", json);
    ///     } catch (e) {
    ///         console.error("Operation failed: ", e);
    ///     }
    /// }
    /// run();
    /// ```
    pub fn to_json(&self) -> Result<String, JsValue> {
        self.maze
            .to_json()
            .map_err(|e| JsValue::from_str(&e.to_string()))
    }
    #[wasm_bindgen]
    /// Initializes the maze instance by reading the JSON string content provided
    ///
    /// # Returns
    ///
    /// This function will return an error if the JSON could not be read
    ///
    /// # Examples
    ///
    /// Create a new maze and initialise it from a JSON string. Then, print
    /// the `cell_type` for each cell.
    ///
    /// ```javascript
    /// // Javascript <script> content:
    ///
    /// import init, { MazeWasm } from 'maze_wasm.js';
    ///
    /// async function run() {
    ///     await init();
    ///
    ///     try {
    ///         let maze = new MazeWasm();
    ///         maze.from_json(`{
    ///             \"id\":\"maze_id\",
    ///             \"name\":\"test\",
    ///             \"definition\": {
    ///                 \"grid\":[
    ///                     [\"S\", \"W\", \" \", \" \", \"W\"],
    ///                     [\" \", \"W\", \" \", \"W\", \" \"],
    ///                     [\" \", \" \", \" \", \"W\", \"F\"],
    ///                     [\"W\", \" \", \"W\", \" \", \" \"],
    ///                     [\" \", \" \", \" \", \"W\", \" \"],
    ///                     [\"W\", \"W\", \" \", \" \", \" \"],
    ///                     [\"W\", \"W\", \" \", \"W\", \" \"]
    ///                 ]
    ///         }}`);
    ///         for (let row  = 0; row < maze.get_row_count(); row ++) {
    ///             for (let col  = 0; col < maze.get_col_count(); col ++) {
    ///                 console.log(`After from_json(), cell_type at (${row}, ${col}) = `, maze.get_cell(row, col).cell_type);
    ///             }
    ///         }
    ///     } catch (e) {
    ///         console.error("Operation failed: ", e);
    ///     }
    /// }
    /// run();
    /// ```
    pub fn from_json(&mut self, json_string: JsValue) -> Result<(), JsValue> {
        let json_str = Self::arg_to_string("json_string", json_string)?;
        self.maze
            .from_json(&json_str)
            .map_err(|e| JsValue::from_str(&e.to_string()))?;
        Ok(())
    }
    #[wasm_bindgen]
    /// Attempts to solve the path between the start and end points defined within the maze instance
    ///
    /// # Returns
    ///
    /// A maze solution ([`MazeSolutionWasm`]) if successful, else an error if the maze could not be solved
    ///
    ///
    /// # Examples
    ///
    /// Initialize a maze from a JSON string, then attempt to solve it and, if successful,
    /// print the maze solution path's points
    ///
    /// ```javascript
    /// // Javascript <script> content:
    ///
    /// import init, { MazeWasm } from 'maze_wasm.js';
    ///
    /// async function run() {
    ///     await init();
    ///
    ///     try {
    ///         let maze = new MazeWasm();
    ///         maze.from_json(`{
    ///             \"id\":\"maze_id\",
    ///             \"name\":\"test\",
    ///             \"definition\": {
    ///                 \"grid\":[
    ///                     [\"S\", \"W\", \" \", \" \", \"W\"],
    ///                     [\" \", \"W\", \" \", \"W\", \" \"],
    ///                     [\" \", \" \", \" \", \"W\", \"F\"],
    ///                     [\"W\", \" \", \"W\", \" \", \" \"],
    ///                     [\" \", \" \", \" \", \"W\", \" \"],
    ///                     [\"W\", \"W\", \" \", \" \", \" \"],
    ///                     [\"W\", \"W\", \" \", \"W\", \" \"]
    ///                 ]
    ///         }}`);
    ///         let solution = maze.solve();
    ///         let solutionPoints = solution.get_path_points();
    ///         console.log("Maze solve() succeeded. Solution points are: ", solutionPoints);
    ///     } catch (e) {
    ///         console.error("Operation failed: ", e);
    ///     }
    /// }
    /// run();
    /// ```
    pub fn solve(&self) -> Result<MazeSolutionWasm, JsValue> {
        let solution = self
            .maze
            .solve()
            .map_err(|e| JsValue::from_str(&e.to_string()))?;
        Ok(MazeSolutionWasm { solution })
    }

    // Private helper functions and methods
    fn js_value_type_str(val: JsValue) -> String {
        if val.is_string() {
            "string".to_string()
        } else if val.as_f64().is_some() {
            "number".to_string()
        } else if val.as_bool().is_some() {
            "boolean".to_string()
        } else if val.is_object() {
            if val.is_null() {
                "null".to_string()
            } else {
                "object".to_string()
            }
        } else if val.is_undefined() {
            "undefined".to_string()
        } else if val.is_symbol() {
            "symbol".to_string()
        } else {
            "unknown".to_string()
        }
    }

    fn js_arg_error_str(
        name: &str,
        expected_type: &str,
        value: JsValue,
        value_type_prefix: &str,
    ) -> JsValue {
        JsValue::from_str(&format!(
            "invalid '{}' argument provided - expected '{}' but '{}{}' provided",
            name,
            expected_type,
            value_type_prefix,
            Self::js_value_type_str(value)
        ))
    }

    fn arg_to_string(name: &str, value: JsValue) -> Result<String, JsValue> {
        if value.is_null() || value.is_undefined() {
            return Err(Self::js_arg_error_str(name, "string", value, ""));
        }
        match value.as_string() {
            Some(s) => Ok(s),
            None => Err(Self::js_arg_error_str(name, "string", value, "")),
        }
    }

    fn arg_to_usize(name: &str, value: JsValue) -> Result<usize, JsValue> {
        if value.is_null() || value.is_undefined() {
            return Err(Self::js_arg_error_str(name, "unsigned integer", value, ""));
        }
        if let Some(number) = value.as_f64() {
            if number >= 0.0 && number.fract() == 0.0 {
                Ok(number as usize)
            } else {
                Err(Self::js_arg_error_str(
                    name,
                    "unsigned integer",
                    value,
                    "negative ",
                ))
            }
        } else {
            Err(Self::js_arg_error_str(name, "unsigned integer", value, ""))
        }
    }

    fn set_cell_values(
        &mut self,
        start_row: JsValue,
        start_col: JsValue,
        end_row: JsValue,
        end_col: JsValue,
        modify_char: char,
    ) -> Result<(), JsValue> {
        let start_row = Self::arg_to_usize("start_row", start_row)?;
        let start_col = Self::arg_to_usize("start_col", start_col)?;
        let end_row = Self::arg_to_usize("end_row", end_row)?;
        let end_col = Self::arg_to_usize("end_col", end_col)?;

        self.maze
            .definition
            .set_value(
                MazePoint {
                    row: start_row,
                    col: start_col,
                },
                MazePoint {
                    row: end_row,
                    col: end_col,
                },
                modify_char,
            )
            .map_err(|e| JsValue::from_str(&e.to_string()))?;
        Ok(())
    }
}