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
//! TODO: GLOBAL DOCS
//!
//! TODO: FINISH DOCS OF THE MODULE
//!
//! # GroupID Delimiters
//! # TODO: ADD FORMATTING AND ESCAPED CHARACTER EXPLANATION

use std::fmt;

/// The delimiter used at the start of a [`GroupID`].
pub const DELIMITER_OPEN_GROUPID: &str = r#"[["#;
/// The delimiter used at the end of a [`GroupID`].
pub const DELIMITER_CLOSE_GROUPID: &str = r#"]]"#;

/// The escaped delimiter, which gets converted to [`DELIMITER_OPEN_GROUPID`] when applied.
pub const DELIMITER_ESCAPED_OPEN_GROUPID: &str = r#"[\["#;
/// The escaped delimiter, which gets converted to [`DELIMITER_CLOSE_GROUPID`] when applied.
pub const DELIMITER_ESCAPED_CLOSE_GROUPID: &str = r#"]\]"#;

/// Enum to store the various types of errors that can cause invalidation of a [`GroupID`].
///
/// # Important
/// When a validity check fails the error gets returned immediately,
/// meaning that if it fails for multiple reasons only the first one is provided.
/// This is the order the [`GroupID`] validity checks get performed:
/// 1. Check for [`DELIMITER_OPEN_GROUPID`] ([`ContainsOpen`](`GroupIDErrorKind::ContainsOpen`))
/// 2. Check for [`DELIMITER_CLOSE_GROUPID`] ([`ContainsClose`](`GroupIDErrorKind::ContainsClose`))
/// 3. Check if non-empty ([`Empty`](`GroupIDErrorKind::Empty`))
///
/// # Example
///
/// ```
/// # use robot_description_builder::identifiers::{GroupIDError, GroupID, GroupIDErrorKind};
/// if let Err(e) = GroupID::is_valid_group_id(&"[[ThisIsInvalid]]") {
///     println!("Invalid GroupID: {:?}", e.kind());
/// #   assert_eq!(e.kind(), &GroupIDErrorKind::ContainsOpen);
/// }
/// # else { unreachable!() }
/// ```
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum GroupIDErrorKind {
	/// `GroupID` being checked contains an unescaped opening `GroupID` delimiter.
	///
	/// This variant will be constructed when the [`GroupID`] being checked contains [`DELIMITER_OPEN_GROUPID`].
	ContainsOpen,
	/// `GroupID` being checked contains an unescaped closing `GroupID` delimiter.
	///
	/// This variant will be constructed when the [`GroupID`] being checked contains [`DELIMITER_CLOSE_GROUPID`].
	ContainsClose,
	/// `GroupID` being checked is empty.
	///
	/// This variant will be constructed when checking the [`GroupID`] validity of an empty string.
	Empty,
}

/// An error which can be returned when checking for a [`GroupID`]'s validity.
///
/// This error is used as an error type for functions which check for [`GroupID`] validity such as [`GroupID::is_valid_group_id`]/
///
/// # TODO: Potential causes ?
///
/// # Example
///
/// ```
/// # use robot_description_builder::identifiers::{GroupIDError, GroupID};
/// if let Err(e) = GroupID::is_valid_group_id(&"[[no]]") {
///     println!("Invalid GroupID: {e}");
/// }
/// # else { unreachable!() }
/// ```
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct GroupIDError {
	/// The invalid [`GroupID`]
	invalid_group_id: String,
	/// The reason why the [`GroupID`] is invalid
	pub(super) kind: GroupIDErrorKind,
}

impl GroupIDError {
	/// Creates a [`GroupIDError`] of kind [`GroupIDErrorKind::ContainsOpen`]
	pub(super) fn new_open(invalid_group_id: &str) -> Self {
		Self {
			invalid_group_id: invalid_group_id.to_string(),
			kind: GroupIDErrorKind::ContainsOpen,
		}
	}

	/// Creates a [`GroupIDError`] of kind [`GroupIDErrorKind::ContainsClose`]
	pub(super) fn new_close(invalid_group_id: &str) -> Self {
		Self {
			invalid_group_id: invalid_group_id.to_string(),
			kind: GroupIDErrorKind::ContainsClose,
		}
	}

	/// Creates a [`GroupIDError`] of kind [`GroupIDErrorKind::Empty`]
	pub(super) fn new_empty() -> Self {
		Self {
			invalid_group_id: String::new(),
			kind: GroupIDErrorKind::Empty,
		}
	}

	/// Returns a reference to a cloned [`String`] of the [`GroupID`], which caused the error.
	pub fn group_id(&self) -> &String {
		&self.invalid_group_id
	}

	/// Outputs the detailed cause of invalidation of the [`GroupID`].
	pub fn kind(&self) -> &GroupIDErrorKind {
		&self.kind
	}
}

impl fmt::Display for GroupIDError {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		match self.kind {
			GroupIDErrorKind::ContainsOpen => write!(
				f,
				"invalid opening delimter (\"{}\") found in GroupID (\"{}\")",
				DELIMITER_OPEN_GROUPID, self.invalid_group_id
			),
			GroupIDErrorKind::ContainsClose => write!(
				f,
				"invalid closing delimiter (\"{}\") found in GroupID (\"{}\")",
				DELIMITER_CLOSE_GROUPID, self.invalid_group_id
			),
			GroupIDErrorKind::Empty => write!(f, "cannot change GroupID to empty string"),
		}
	}
}

impl std::error::Error for GroupIDError {}

/// Checks if the supplied `&str` is a valid [`GroupID`].
///
/// Returns a result type containing the valid `GroupID` as an `&str`, or an error with the invalidation reason.  
fn check_group_id_validity(new_group_id: &str) -> Result<&str, GroupIDError> {
	// !(new_group_id.contains(DELIMTER_OPEN_GROUPID)
	// 	|| new_group_id.contains(DELIMTER_CLOSE_GROUPID)
	// 	|| new_group_id.is_empty());

	// TODO: Maybe also check for '"'

	if new_group_id.contains(DELIMITER_OPEN_GROUPID) {
		Err(GroupIDError::new_open(new_group_id))
	} else if new_group_id.contains(DELIMITER_CLOSE_GROUPID) {
		Err(GroupIDError::new_close(new_group_id))
	} else if new_group_id.is_empty() {
		Err(GroupIDError::new_empty())
	} else {
		Ok(new_group_id)
	}
}

/// Replaces the [`GroupID`] delimiters in the supplied `&str`
///
/// `replace_group_id_delimiters` creates a new `String`, and copies the data from the provided string slice into it.
/// While doing so, it attempts to find matches of a the non-escaped and escapded `GroupID` delimiters.
/// If it finds any, it replaces them with the replacements specified below.
///
/// The following replacements get made:
///  - [`DELIMITER_OPEN_GROUPID`] with `""`
///  - [`DELIMITER_CLOSE_GROUPID`] with `""`
///  - [`DELIMITER_ESCAPED_OPEN_GROUPID`] with [`DELIMITER_OPEN_GROUPID`]
///  - [`DELIMITER_ESCAPED_CLOSE_GROUPID`] with [`DELIMITER_CLOSE_GROUPID`]
fn replace_group_id_delimiters(input: &str) -> String {
	input
		.replace(DELIMITER_OPEN_GROUPID, "")
		.replace(DELIMITER_CLOSE_GROUPID, "")
		.replace(DELIMITER_ESCAPED_OPEN_GROUPID, DELIMITER_OPEN_GROUPID)
		.replace(DELIMITER_ESCAPED_CLOSE_GROUPID, DELIMITER_CLOSE_GROUPID)
}

/// Format and validation trait for `GroupID`s
///
/// This trait is used to expand [`String`] and string slices for validity checks and `GroupID` escaped formatting applied
///
/// For more information on `GroupID` changing and escaping, see [the module-level documentation](`crate::identifiers`).
///
/// # TODO: Examples
/// TODO: Maybe skip examples for this one
pub trait GroupID {
	/// Checks if the current `GroupID` is Valid
	///
	/// If the current [`GroupID`] is valid, the [`GroupID`] get's returned as `Ok(&str)`.
	///
	/// Otherwise an error of type [`GroupIDError`] is returned describing why the current [`GroupID`] is invalid.  
	fn is_valid_group_id(&self) -> Result<&str, GroupIDError>;

	/// Return an cloned `String` of the current `GroupID` with the delimiters replaced.
	///
	/// TODO: UPGRADE OR REFERENCE ANOTHER DOCUMENTATION TO PREVENT DISCRAPENCIES BETWEEN DOCS
	///
	/// Returns a cloned [`String`] with the following replacements:
	///  - [`DELIMITER_OPEN_GROUPID`] with `""`
	///  - [`DELIMITER_CLOSE_GROUPID`] with `""`
	///  - [`DELIMITER_ESCAPED_OPEN_GROUPID`] with [`DELIMITER_OPEN_GROUPID`]
	///  - [`DELIMITER_ESCAPED_CLOSE_GROUPID`] with [`DELIMITER_CLOSE_GROUPID`]
	fn display(&self) -> String;

	/// Maybe wrong place. TODO: Consider moving to `GroupIDChanger`
	///
	/// TODO:
	/// - Move?
	/// - Document
	/// - Test
	fn get_group_id(&self) -> Option<&str>;
}

impl GroupID for String {
	fn is_valid_group_id(&self) -> Result<&str, GroupIDError> {
		check_group_id_validity(self)
	}

	fn display(&self) -> String {
		replace_group_id_delimiters(self)
	}

	/// Maybe wrong place. TODO: Consider moving to `GroupIDChanger`
	fn get_group_id(&self) -> Option<&str> {
		self.split_once(DELIMITER_OPEN_GROUPID)
			.and_then(|(_, near_group_id)| {
				near_group_id
					.rsplit_once(DELIMITER_CLOSE_GROUPID)
					.map(|(group_id, _)| group_id)
			})
	}
}

impl GroupID for &str {
	fn is_valid_group_id(&self) -> Result<&str, GroupIDError> {
		check_group_id_validity(self)
	}

	fn display(&self) -> String {
		replace_group_id_delimiters(self)
	}

	/// Maybe wrong place. TODO: Consider moving to `GroupIDChanger`
	fn get_group_id(&self) -> Option<&str> {
		self.split_once(DELIMITER_OPEN_GROUPID)
			.and_then(|(_, near_group_id)| {
				near_group_id
					.rsplit_once(DELIMITER_CLOSE_GROUPID)
					.map(|(group_id, _)| group_id)
			})
	}
}

/// Used for `GroupID` modifications on buildertrees.
///
/// Implementing this trait allows for the modification of identification string (often `name` field) of its implementor and his children.
///
/// The following operations can be done:
///  - Replacing the [`GroupID`] section of the identification string.
///  - Appling the [`GroupID` delimiter transformations](crate::identifiers#groupid-delimiters)
///
/// This should be achieved by recursively calling the desired method on the children of the implementor.
///
/// # Examples
///
/// Impemtation of `GroupIDChanger` for on an example struct tree:
///
/// ```
/// use robot_description_builder::identifiers::{GroupIDChanger,GroupIDErrorKind};
///
/// #[derive(Debug, PartialEq, Eq, Clone)]
/// struct ChildStruct {
///     name: String
/// }
///
/// impl GroupIDChanger for ChildStruct {
///     unsafe fn change_group_id_unchecked(&mut self, new_group_id: &str) {
///         self.name.change_group_id_unchecked(new_group_id);
///     }
///
///     fn apply_group_id(&mut self) {
///         self.name.apply_group_id();
///     }
/// }
///
/// #[derive(Debug, PartialEq, Eq, Clone)]
/// struct ParentStruct {
///     name: String,
///     child: Option<ChildStruct>
/// }
///
/// impl GroupIDChanger for ParentStruct {
///     unsafe fn change_group_id_unchecked(&mut self, new_group_id: &str) {
///         self.name.change_group_id_unchecked(new_group_id);
///         if let Some(child) = self.child.as_mut() {
///             child.change_group_id_unchecked(new_group_id);
///         }
///     }
///
///     fn apply_group_id(&mut self) {
///         self.name.apply_group_id();
///         if let Some(child) = self.child.as_mut() {
///             child.apply_group_id();
///         }
///     }
/// }
///
/// let example_tree = ParentStruct{
///         name: "tree_[[0]]".into(),
///         child: Some(ChildStruct{name:"tree_child_[[0]][\\[".into()})
///     };
///
/// // Appling a GroupID
/// let mut applied_tree = example_tree.clone();
/// applied_tree.apply_group_id();
/// assert_eq!(
///     applied_tree,
///     ParentStruct{
///         name: "tree_0".into(),
///         child: Some(ChildStruct{name:"tree_child_0[[".into()})
///     }
/// );
///
/// // Changing the GroupID
/// let mut changed_tree = example_tree.clone();
/// assert!(changed_tree.change_group_id("1").is_ok());
/// assert_eq!(
///     changed_tree,
///     ParentStruct{
///         name: "tree_[[1]]".into(),
///         child: Some(ChildStruct{name:"tree_child_[[1]][\\[".into()})
///     }
/// );
///
/// // Invalid GroupID
/// let mut failed_tree = example_tree.clone();
/// assert_eq!(changed_tree.change_group_id("").unwrap_err().kind(), &GroupIDErrorKind::Empty);
/// // The tree remains unchanged
/// assert_eq!(failed_tree, example_tree);
/// ```
pub trait GroupIDChanger {
	/// Replaces the `GroupID` of the builder tree with `new_group_id`.
	///
	/// If `new_group_id` is a valid [`GroupID`] then the `GroupID` of the whole buildertree is replaced.
	/// Otherwise, this method fails returning an error explaing the invalidation.
	///
	/// For performance reasons the check only get's performed here,
	/// when this succeeds [`change_group_id_unchecked`][GroupIDChanger::change_group_id_unchecked] is used to perform the actual updating.
	fn change_group_id(&mut self, new_group_id: impl GroupID) -> Result<(), GroupIDError> {
		unsafe {
			Self::change_group_id_unchecked(self, new_group_id.is_valid_group_id()?);
		};
		Ok(())
	}

	/// Unchecked replacement of the `GroupID` of the builder tree with `new_group_id`.
	///
	/// Changes the [`GroupID`] of the identification string of the current builder tree without checking if the `new_group_id` is valid.
	/// This should be achieved by calling this method on all its implementors childeren and its identification string often called `name`.
	///
	/// # Safety
	///
	/// This function should be called with a valid [`GroupID`].
	/// It is recommended to use [`change_group_id`](GroupIDChanger::change_group_id) instead.
	unsafe fn change_group_id_unchecked(&mut self, new_group_id: &str);

	/// Applies `GroupID` delimiter replacements.
	///
	/// Replaces the [`GroupID`] delimiters in the current builder tree.
	///
	/// TODO: REFERENCE MODULE DOC ABOUT GroupID Delimiters and replacements
	///
	/// -----
	/// TODO: UPGRADE
	///
	/// Replaces:
	///  - [`DELIMITER_OPEN_GROUPID`] with `""`
	///  - [`DELIMITER_CLOSE_GROUPID`] with `""`
	///  - [`DELIMITER_ESCAPED_OPEN_GROUPID`] with [`DELIMITER_OPEN_GROUPID`]
	///  - [`DELIMITER_ESCAPED_CLOSE_GROUPID`] with [`DELIMITER_CLOSE_GROUPID`]
	fn apply_group_id(&mut self);
}

impl GroupIDChanger for String {
	unsafe fn change_group_id_unchecked(&mut self, new_group_id: &str) {
		if self.matches(DELIMITER_OPEN_GROUPID).count() == 1
			&& self.matches(DELIMITER_CLOSE_GROUPID).count() == 1
		{
			if let Some((pre, _, post)) =
				self.split_once(DELIMITER_OPEN_GROUPID)
					.and_then(|(pre, remainder)| {
						remainder
							.split_once(DELIMITER_CLOSE_GROUPID)
							.map(|(group_id, post)| (pre, group_id, post))
					}) {
				let new = format!(
					"{}{}{}{}{}",
					pre, DELIMITER_OPEN_GROUPID, new_group_id, DELIMITER_CLOSE_GROUPID, post
				);

				#[cfg(any(feature = "logging", test))]
				log::info!(
					target: "GroupIDChanger",
					"The identification string \"{}\" was replaced by \"{}\"",
					self, new
				);

				*self = new;
			}
		} else {
			#[cfg(any(feature = "logging", test))]
			log::info!(
				target: "GroupIDChanger",
				"The changing of the GroupID of \"{}\" was skipped due to not having exactly 1 opening and 1 closing delimiter",
				self
			);
		}
	}

	fn apply_group_id(&mut self) {
		// Maybe checking is uncessesary
		let open_count = self.matches(DELIMITER_OPEN_GROUPID).count();
		let close_count = self.matches(DELIMITER_CLOSE_GROUPID).count();

		if (open_count == 1 && close_count == 1) || (open_count == 0 && close_count == 0) {
			let new = Self::display(self);

			#[cfg(any(feature = "logging", test))]
			log::info!(
				target: "GroupIDChanger",
				"Applied GroupID delimiter transformations to \"{}\", changed to \"{}\"",
				self, new
			);

			*self = new;
		} else {
			#[cfg(any(feature = "logging", test))]
			log::info!(
				target: "GroupIDChanger",
				"The GroupID delimiters transformations where not applied to \"{}\", because {}",
				self,
				match (open_count, close_count) {
					(0, 0) | (1, 1) => unreachable!(),
					(1, 0) => format!("of an unclosed GroupID field. (missing \"{DELIMITER_CLOSE_GROUPID}\")"),
					(0, 1) => format!("of an unopened GroupID field. (missing \"{DELIMITER_OPEN_GROUPID}\")"),
					(0 | 1, _) => format!("of excess closing delimeters (\"{DELIMITER_CLOSE_GROUPID}\"), expected {open_count} closing tags based on amount of opening tags, got {close_count} closing tags"),
					(_, 0 | 1) => format!("of excess opening delimeters (\"{DELIMITER_OPEN_GROUPID}\"), expected {close_count} opening tags based on amount of closing tags, got {open_count} opening tags"),
					(_, _) => format!("of unexpected amount of opening and closing tags, got (Open, close) = ({open_count}, {close_count}), expected (0, 0) or (1, 1)")
				}
			);
		}
	}
}

#[cfg(test)]
mod tests {
	use super::{
		check_group_id_validity, replace_group_id_delimiters, GroupIDError, GroupIDErrorKind,
		DELIMITER_ESCAPED_CLOSE_GROUPID, DELIMITER_ESCAPED_OPEN_GROUPID,
	};
	use test_log::test;

	#[test]
	fn test_check_group_id_validity() {
		assert_eq!(
			check_group_id_validity("[[---"),
			Err(GroupIDError {
				invalid_group_id: "[[---".to_string(),
				kind: GroupIDErrorKind::ContainsOpen
			})
		);

		assert_eq!(
			check_group_id_validity("smiley? :]]"),
			Err(GroupIDError {
				invalid_group_id: "smiley? :]]".to_string(),
				kind: GroupIDErrorKind::ContainsClose
			})
		);

		assert_eq!(
			check_group_id_validity(""),
			Err(GroupIDError {
				invalid_group_id: String::new(),
				kind: GroupIDErrorKind::Empty
			})
		);

		assert_eq!(check_group_id_validity("L02"), Ok("L02"));
		assert_eq!(check_group_id_validity("left_arm"), Ok("left_arm"));
		assert_eq!(
			check_group_id_validity(&String::from("Left[4]")),
			Ok("Left[4]")
		);
		assert_eq!(
			check_group_id_validity(&format!(
				"Right{}99999999999999{}_final_count_down",
				DELIMITER_ESCAPED_OPEN_GROUPID, DELIMITER_ESCAPED_CLOSE_GROUPID
			)),
			Ok(r#"Right[\[99999999999999]\]_final_count_down"#)
		);
	}

	#[test]
	fn test_replace_group_id_delimiters() {
		assert_eq!(replace_group_id_delimiters("nothing"), "nothing");

		// Delimiters
		assert_eq!(
			replace_group_id_delimiters("[[Hopefully Not Hidden]]"),
			"Hopefully Not Hidden"
		);
		assert_eq!(replace_group_id_delimiters("colo[[[u]]]r"), "colo[u]r");
		assert_eq!(
			replace_group_id_delimiters("Before[[[[Anything]]]]After"),
			"BeforeAnythingAfter"
		);

		// Escaped
		assert_eq!(
			replace_group_id_delimiters("Obsidian Internal Link [\\[Anything]\\]"),
			"Obsidian Internal Link [[Anything]]"
		);
		assert_eq!(
			replace_group_id_delimiters("Front[\\[:[\\[Center]\\]:]\\]Back"),
			"Front[[:[[Center]]:]]Back"
		);

		// Mixed
		assert_eq!(
			replace_group_id_delimiters("multi_groupid_Leg_[\\[L04]\\]_Claw_[[L01]]"),
			"multi_groupid_Leg_[[L04]]_Claw_L01"
		);
	}

	mod group_id {
		use super::{test, DELIMITER_ESCAPED_CLOSE_GROUPID, DELIMITER_ESCAPED_OPEN_GROUPID};
		use crate::identifiers::{GroupID, GroupIDError, GroupIDErrorKind};

		#[test]
		/// GroupID::is_valid_group_id()
		fn is_valid_group_id() {
			assert_eq!(
				"[[---".is_valid_group_id(),
				Err(GroupIDError {
					invalid_group_id: "[[---".to_string(),
					kind: GroupIDErrorKind::ContainsOpen
				})
			);

			assert_eq!(
				"smiley? :]]".is_valid_group_id(),
				Err(GroupIDError {
					invalid_group_id: "smiley? :]]".to_string(),
					kind: GroupIDErrorKind::ContainsClose
				})
			);

			assert_eq!(
				"".is_valid_group_id(),
				Err(GroupIDError {
					invalid_group_id: String::new(),
					kind: GroupIDErrorKind::Empty
				})
			);

			assert_eq!("L02".is_valid_group_id(), Ok("L02"));
			assert_eq!("left_arm".is_valid_group_id(), Ok("left_arm"));
			assert_eq!("Left[4]".is_valid_group_id(), Ok("Left[4]"));
			assert_eq!(
				format!(
					"Right{}99999999999999{}_final_count_down",
					DELIMITER_ESCAPED_OPEN_GROUPID, DELIMITER_ESCAPED_CLOSE_GROUPID
				)
				.is_valid_group_id(),
				Ok(r#"Right[\[99999999999999]\]_final_count_down"#)
			);
		}

		#[test]
		fn display() {
			assert_eq!("nothing".display(), "nothing");

			// Delimiters
			assert_eq!("[[Hopefully Not Hidden]]".display(), "Hopefully Not Hidden");
			assert_eq!("colo[[[u]]]r".display(), "colo[u]r");
			assert_eq!("colo[[[u]]]r".to_string().display(), "colo[u]r");
			assert_eq!(
				"Before[[[[Anything]]]]After".display(),
				"BeforeAnythingAfter"
			);

			// Escaped
			assert_eq!(
				"Obsidian Internal Link [\\[Anything]\\]".display(),
				"Obsidian Internal Link [[Anything]]"
			);
			assert_eq!(
				"Front[\\[:[\\[Center]\\]:]\\]Back".display(),
				"Front[[:[[Center]]:]]Back"
			);

			// Mixed
			assert_eq!(
				"multi_groupid_Leg_[\\[L04]\\]_Claw_[[L01]]".display(),
				"multi_groupid_Leg_[[L04]]_Claw_L01"
			);
			// Mixed
			assert_eq!(
				"multi_groupid_Leg_[\\[L04]\\]_Claw_[[L01]]"
					.to_string()
					.display(),
				"multi_groupid_Leg_[[L04]]_Claw_L01"
			);
		}
	}

	mod group_id_changer {
		use super::test;
		use crate::identifiers::{GroupIDChanger, GroupIDError, GroupIDErrorKind};

		fn test_change_group_id_unchecked(s: impl Into<String>, new_group_id: &str, result: &str) {
			let mut s: String = s.into();
			unsafe {
				s.change_group_id_unchecked(new_group_id);
			}
			assert_eq!(s, result)
		}

		#[test]
		fn change_group_id_unchecked() {
			test_change_group_id_unchecked("nothing", "R02", "nothing");

			// Delimiters
			test_change_group_id_unchecked("[[Hopefully Not Hidden]]", "R02", "[[R02]]");
			test_change_group_id_unchecked("colo[[[u]]]r", "u", "colo[[u]]]r");
			test_change_group_id_unchecked(
				// TODO: Is this final behavior?
				"Before[[[[Anything]]]]After",
				"Sunrise",
				"Before[[[[Anything]]]]After", // "BeforeSunriseAfter",
			);

			// Escaped
			test_change_group_id_unchecked(
				"Obsidian Internal Link [\\[Anything]\\]",
				".....",
				"Obsidian Internal Link [\\[Anything]\\]",
			);
			test_change_group_id_unchecked(
				"Front[\\[:[\\[Center]\\]:]\\]Back",
				".....",
				"Front[\\[:[\\[Center]\\]:]\\]Back",
			);

			// Mixed
			test_change_group_id_unchecked(
				"multi_groupid_Leg_[\\[L04]\\]_Claw_[[L01]]",
				"R09",
				"multi_groupid_Leg_[\\[L04]\\]_Claw_[[R09]]",
			);
			test_change_group_id_unchecked(
				"Front[\\[:[[Center]]:]\\]Back",
				"Middle",
				"Front[\\[:[[Middle]]:]\\]Back",
			);

			// UNCHECKED BEHAVIOR
			test_change_group_id_unchecked(
				"multi_groupid_Leg_[\\[L04]\\]_Claw_[[L01]]",
				"[[R08]]",
				"multi_groupid_Leg_[\\[L04]\\]_Claw_[[[[R08]]]]",
			);
			test_change_group_id_unchecked(
				"Front[\\[:[[Center]]:]\\]Back",
				"",
				"Front[\\[:[[]]:]\\]Back",
			);
		}

		fn test_change_group_id(
			s: impl Into<String>,
			new_group_id: &str,
			func_result: Result<(), GroupIDError>,
			new_identifier: &str,
		) {
			let mut s: String = s.into();
			assert_eq!(s.change_group_id(new_group_id), func_result);
			assert_eq!(s, new_identifier);
		}

		#[test]
		fn change_group_id() {
			test_change_group_id("nothing", "R02", Ok(()), "nothing");

			// Delimiters
			test_change_group_id("[[Hopefully Not Hidden]]", "R02", Ok(()), "[[R02]]");
			test_change_group_id("colo[[[u]]]r", "u", Ok(()), "colo[[u]]]r");
			test_change_group_id(
				// TODO: Is this final behavior?
				"Before[[[[Anything]]]]After",
				"Sunrise",
				Ok(()),
				"Before[[[[Anything]]]]After", // "BeforeSunriseAfter",
			);

			// Escaped
			test_change_group_id(
				"Obsidian Internal Link [\\[Anything]\\]",
				".....",
				Ok(()),
				"Obsidian Internal Link [\\[Anything]\\]",
			);
			test_change_group_id(
				"Front[\\[:[\\[Center]\\]:]\\]Back",
				".....",
				Ok(()),
				"Front[\\[:[\\[Center]\\]:]\\]Back",
			);

			// Mixed
			test_change_group_id(
				"multi_groupid_Leg_[\\[L04]\\]_Claw_[[L01]]",
				"R09",
				Ok(()),
				"multi_groupid_Leg_[\\[L04]\\]_Claw_[[R09]]",
			);
			test_change_group_id(
				"Front[\\[:[[Center]]:]\\]Back",
				"Middle",
				Ok(()),
				"Front[\\[:[[Middle]]:]\\]Back",
			);

			// UNCHECKED BEHAVIOR
			test_change_group_id(
				"multi_groupid_Leg_[\\[L04]\\]_Claw_[[L01]]",
				"[[R08]]",
				Err(GroupIDError {
					invalid_group_id: "[[R08]]".into(),
					kind: GroupIDErrorKind::ContainsOpen,
				}),
				"multi_groupid_Leg_[\\[L04]\\]_Claw_[[L01]]",
			);
			test_change_group_id(
				"Front[\\[:[[Center]]:]\\]Back",
				"",
				Err(GroupIDError {
					invalid_group_id: String::new(),
					kind: GroupIDErrorKind::Empty,
				}),
				"Front[\\[:[[Center]]:]\\]Back",
			);
		}

		fn test_apply_group_id(s: impl Into<String>, result: &str) {
			let mut s: String = s.into();
			s.apply_group_id();
			assert_eq!(s, result);
		}

		#[test]
		fn apply_group_id() {
			test_apply_group_id("nothing", "nothing");

			// Delimiters
			test_apply_group_id("[[Hopefully Not Hidden]]", "Hopefully Not Hidden");
			test_apply_group_id("colo[[[u]]]r", "colo[u]r");
			test_apply_group_id(
				// TODO: Is this final behavior?
				"Before[[[[Anything]]]]After",
				"Before[[[[Anything]]]]After",
			);

			// Escaped
			test_apply_group_id(
				"Obsidian Internal Link [\\[Anything]\\]",
				"Obsidian Internal Link [[Anything]]",
			);
			test_apply_group_id(
				"Front[\\[:[\\[Center]\\]:]\\]Back",
				"Front[[:[[Center]]:]]Back",
			);

			// Mixed
			test_apply_group_id(
				"multi_groupid_Leg_[\\[L04]\\]_Claw_[[L01]]",
				"multi_groupid_Leg_[[L04]]_Claw_L01",
			);
			test_apply_group_id("Front[\\[:[[Center]]:]\\]Back", "Front[[:Center:]]Back");

			test_apply_group_id(
				"multi_groupid_Leg_[\\[L04]\\]]_Claw_[[L01]]",
				"multi_groupid_Leg_[\\[L04]\\]]_Claw_[[L01]]",
			);
		}
	}
}