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
//! Traits and structs used by prompts to validate user input before
//! returning the values to their callers.
//!
//! Validators receive the user input to a given prompt and decide whether
//! they are valid, returning `Ok(Validation::Valid)` in the process, or
//! invalid, returning `Ok(Validation::Invalid(ErrorMessage))`, where the
//! `ErrorMessage` content is an error message to be displayed to the end user.
//!
//! Validators can also return errors, which propagate to the caller prompt
//! and cause the prompt to return the error.
//!
//! This module also provides several macros as shorthands to the struct
//! constructor functions, exported with the `macros` feature.

use dyn_clone::DynClone;

use crate::{error::CustomUserError, list_option::ListOption};

/// Error message that is displayed to the users when their input is considered not
/// valid by registered validators.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ErrorMessage {
    /// No custom message is defined, a standard one defined in the set
    /// [`RenderConfig`](crate::ui::RenderConfig) is used instead.
    Default,

    /// Custom error message, used instead of the standard one.
    Custom(String),
}

impl Default for ErrorMessage {
    fn default() -> Self {
        ErrorMessage::Default
    }
}

impl<T> From<T> for ErrorMessage
where
    T: ToString,
{
    fn from(msg: T) -> Self {
        Self::Custom(msg.to_string())
    }
}

/// The result type of validation operations when the execution of the validator
/// function succeeds.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Validation {
    /// Variant that indicates that the input value is valid according to the validator.
    Valid,

    /// Variant that indicates that the input value is invalid according to the validator.
    ///
    /// The member represents a custom error message that will be displayed to the user when present.
    /// When empty a standard error message, configured via the RenderConfig struct, will be shown
    /// instead.
    Invalid(ErrorMessage),
}

/// Validator that receives a string slice as the input, such as [`Text`](crate::Text) and
/// [`Password`](crate::Password).
///
/// If the input provided by the user is valid, your validator should return `Ok(Validation::Valid)`.
///
/// If the input is not valid, your validator should return `Ok(Validation::Invalid(ErrorMessage))`,
/// where the content of `ErrorMessage` is recommended to be a string whose content will be displayed
/// to the user as an error message. It is also recommended that this value gives a helpful feedback to the user.
///
/// # Examples
///
/// ```
/// use inquire::validator::{StringValidator, Validation};
///
/// let validator = |input: &str| match input.chars().find(|c| c.is_numeric()) {
///     Some(_) => Ok(Validation::Valid),
///     None => Ok(Validation::Invalid(
///         "Your password should contain at least 1 digit".into(),
///     )),
/// };
///
/// assert_eq!(Validation::Valid, validator.validate("hunter2")?);
/// assert_eq!(
///     Validation::Invalid("Your password should contain at least 1 digit".into()),
///     validator.validate("password")?
/// );
/// # Ok::<(), inquire::error::CustomUserError>(())
/// ```
pub trait StringValidator: DynClone {
    /// Confirm the given input string is a valid value.
    fn validate(&self, input: &str) -> Result<Validation, CustomUserError>;
}

impl Clone for Box<dyn StringValidator> {
    fn clone(&self) -> Self {
        dyn_clone::clone_box(&**self)
    }
}

impl<F> StringValidator for F
where
    F: Fn(&str) -> Result<Validation, CustomUserError> + Clone,
{
    fn validate(&self, input: &str) -> Result<Validation, CustomUserError> {
        (self)(input)
    }
}

/// Validator used in [`DateSelect`](crate::DateSelect) prompts.
///
/// If the input provided by the user is valid, your validator should return `Ok(Validation::Valid)`.
///
/// If the input is not valid, your validator should return `Ok(Validation::Invalid(ErrorMessage))`,
/// where the content of `ErrorMessage` is recommended to be a string whose content will be displayed
/// to the user as an error message. It is also recommended that this value gives a helpful feedback to the user.
///
/// # Examples
///
/// ```
/// use chrono::{Datelike, NaiveDate, Weekday};
/// use inquire::validator::{DateValidator, Validation};
///
/// let validator = |input: NaiveDate| {
///     if input.weekday() == Weekday::Sat || input.weekday() == Weekday::Sun {
///         Ok(Validation::Invalid("Weekends are not allowed".into()))
///     } else {
///         Ok(Validation::Valid)
///     }
/// };
///
/// assert_eq!(Validation::Valid, validator.validate(NaiveDate::from_ymd(2021, 7, 26))?);
/// assert_eq!(
///     Validation::Invalid("Weekends are not allowed".into()),
///     validator.validate(NaiveDate::from_ymd(2021, 7, 25))?
/// );
/// # Ok::<(), inquire::error::CustomUserError>(())
/// ```
#[cfg(feature = "date")]
pub trait DateValidator: DynClone {
    /// Confirm the given input date is a valid value.
    fn validate(&self, input: chrono::NaiveDate) -> Result<Validation, CustomUserError>;
}

#[cfg(feature = "date")]
impl Clone for Box<dyn DateValidator> {
    fn clone(&self) -> Self {
        dyn_clone::clone_box(&**self)
    }
}

#[cfg(feature = "date")]
impl<F> DateValidator for F
where
    F: Fn(chrono::NaiveDate) -> Result<Validation, CustomUserError> + Clone,
{
    fn validate(&self, input: chrono::NaiveDate) -> Result<Validation, CustomUserError> {
        (self)(input)
    }
}

/// Validator used in [`MultiSelect`](crate::MultiSelect) prompts.
///
/// If the input provided by the user is valid, your validator should return `Ok(Validation::Valid)`.
///
/// If the input is not valid, your validator should return `Ok(Validation::Invalid(ErrorMessage))`,
/// where the content of `ErrorMessage` is recommended to be a string whose content will be displayed
/// to the user as an error message. It is also recommended that this value gives a helpful feedback to the user.
///
/// # Examples
///
/// ```
/// use inquire::list_option::ListOption;
/// use inquire::validator::{MultiOptionValidator, Validation};
///
/// let validator = |input: &[ListOption<&&str>]| {
///     if input.len() <= 2 {
///         Ok(Validation::Valid)
///     } else {
///         Ok(Validation::Invalid("You should select at most two options".into()))
///     }
/// };
///
/// let mut ans = vec![ListOption::new(0, &"a"), ListOption::new(1, &"b")];
///
/// assert_eq!(Validation::Valid, validator.validate(&ans[..])?);
///
/// ans.push(ListOption::new(3, &"d"));
/// assert_eq!(
///     Validation::Invalid("You should select at most two options".into()),
///     validator.validate(&ans[..])?
/// );
/// # Ok::<(), inquire::error::CustomUserError>(())
/// ```
pub trait MultiOptionValidator<T: ?Sized>: DynClone {
    /// Confirm the given input list is a valid value.
    fn validate(&self, input: &[ListOption<&T>]) -> Result<Validation, CustomUserError>;
}

impl<T> Clone for Box<dyn MultiOptionValidator<T>> {
    fn clone(&self) -> Self {
        dyn_clone::clone_box(&**self)
    }
}

impl<F, T> MultiOptionValidator<T> for F
where
    F: Fn(&[ListOption<&T>]) -> Result<Validation, CustomUserError> + Clone,
    T: ?Sized,
{
    fn validate(&self, input: &[ListOption<&T>]) -> Result<Validation, CustomUserError> {
        (self)(input)
    }
}

/// Validator used in [`CustomType`](crate::CustomType) prompts.
///
/// If the input provided by the user is valid, your validator should return `Ok(Validation::Valid)`.
///
/// If the input is not valid, your validator should return `Ok(Validation::Invalid(ErrorMessage))`,
/// where the content of `ErrorMessage` is recommended to be a string whose content will be displayed
/// to the user as an error message. It is also recommended that this value gives a helpful feedback to the user.
///
/// # Examples
///
/// ```
/// use inquire::list_option::ListOption;
/// use inquire::validator::{MultiOptionValidator, Validation};
///
/// let validator = |input: &[ListOption<&&str>]| {
///     if input.len() <= 2 {
///         Ok(Validation::Valid)
///     } else {
///         Ok(Validation::Invalid("You should select at most two options".into()))
///     }
/// };
///
/// let mut ans = vec![ListOption::new(0, &"a"), ListOption::new(1, &"b")];
///
/// assert_eq!(Validation::Valid, validator.validate(&ans[..])?);
///
/// ans.push(ListOption::new(3, &"d"));
/// assert_eq!(
///     Validation::Invalid("You should select at most two options".into()),
///     validator.validate(&ans[..])?
/// );
/// # Ok::<(), inquire::error::CustomUserError>(())
/// ```
pub trait CustomTypeValidator<T: ?Sized>: DynClone {
    /// Confirm the given input list is a valid value.
    fn validate(&self, input: &T) -> Result<Validation, CustomUserError>;
}

impl<T> Clone for Box<dyn CustomTypeValidator<T>> {
    fn clone(&self) -> Self {
        dyn_clone::clone_box(&**self)
    }
}

impl<F, T> CustomTypeValidator<T> for F
where
    F: Fn(&T) -> Result<Validation, CustomUserError> + Clone,
    T: ?Sized,
{
    fn validate(&self, input: &T) -> Result<Validation, CustomUserError> {
        (self)(input)
    }
}

/// Custom trait to call correct method to retrieve input length.
///
/// The method can vary depending on the type of input.
///
/// String inputs should count the number of graphemes, via
/// `.graphemes(true).count()`, instead of the number of bytes
/// via `.len()`. While simple slices should keep using `.len()`
pub trait InquireLength {
    /// String inputs should count the number of graphemes, via
    /// `.graphemes(true).count()`, instead of the number of bytes
    /// via `.len()`. While simple slices keep using `.len()`
    fn inquire_length(&self) -> usize;
}

impl InquireLength for &str {
    fn inquire_length(&self) -> usize {
        use unicode_segmentation::UnicodeSegmentation;

        self.graphemes(true).count()
    }
}

impl<T> InquireLength for &[T] {
    fn inquire_length(&self) -> usize {
        self.len()
    }
}

/// Built-in validator that checks whether the answer is not empty.
///
/// # Examples
///
/// ```
/// use inquire::validator::{StringValidator, Validation, ValueRequiredValidator};
///
/// let validator = ValueRequiredValidator::default();
/// assert_eq!(Validation::Valid, validator.validate("Generic input")?);
/// assert_eq!(Validation::Invalid("A response is required.".into()), validator.validate("")?);
///
/// let validator = ValueRequiredValidator::new("No empty!");
/// assert_eq!(Validation::Valid, validator.validate("Generic input")?);
/// assert_eq!(Validation::Invalid("No empty!".into()), validator.validate("")?);
/// # Ok::<(), inquire::error::CustomUserError>(())
/// ```
#[derive(Clone)]
pub struct ValueRequiredValidator {
    message: String,
}

impl ValueRequiredValidator {
    /// Create a new instance of this validator with given error message.
    pub fn new(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
        }
    }
}

impl Default for ValueRequiredValidator {
    /// Create a new instance of this validator with the default error message
    /// `A response is required`.
    fn default() -> Self {
        Self {
            message: "A response is required.".to_owned(),
        }
    }
}

impl StringValidator for ValueRequiredValidator {
    fn validate(&self, input: &str) -> Result<Validation, CustomUserError> {
        Ok(if input.is_empty() {
            Validation::Invalid(self.message.as_str().into())
        } else {
            Validation::Valid
        })
    }
}

/// Shorthand for the built-in [`ValueRequiredValidator`] that checks whether the answer is not
/// empty.
///
/// # Arguments
///
/// * `$message` - optional - Error message returned by the validator.
///   Defaults to "A response is required."
///
/// # Examples
///
/// ```
/// use inquire::{required, validator::{StringValidator, Validation}};
///
/// let validator = required!();
/// assert_eq!(Validation::Valid, validator.validate("Generic input")?);
/// assert_eq!(Validation::Invalid("A response is required.".into()), validator.validate("")?);
///
/// let validator = required!("No empty!");
/// assert_eq!(Validation::Valid, validator.validate("Generic input")?);
/// assert_eq!(Validation::Invalid("No empty!".into()), validator.validate("")?);
/// # Ok::<(), inquire::error::CustomUserError>(())
/// ```
#[macro_export]
#[cfg(feature = "macros")]
macro_rules! required {
    () => {
        $crate::validator::ValueRequiredValidator::default()
    };

    ($message:expr) => {
        $crate::validator::ValueRequiredValidator::new($message)
    };
}

/// Built-in validator that checks whether the answer length is smaller than
/// or equal to the specified threshold.
///
/// The validator uses a custom-built length function that
/// has a special implementation for strings which counts the number of
/// graphemes. See this [StackOverflow question](https://stackoverflow.com/questions/46290655/get-the-string-length-in-characters-in-rust).
///
/// # Examples
///
/// ```
/// use inquire::validator::{MaxLengthValidator, StringValidator, Validation};
///
/// let validator = MaxLengthValidator::new(5);
/// assert_eq!(Validation::Valid, validator.validate("Good")?);
/// assert_eq!(
///     Validation::Invalid("The length of the response should be at most 5".into()),
///     validator.validate("Terrible")?,
/// );
///
/// let validator = MaxLengthValidator::new(5).with_message("Not too large!");
/// assert_eq!(Validation::Valid, validator.validate("Good")?);
/// assert_eq!(Validation::Invalid("Not too large!".into()), validator.validate("Terrible")?);
/// # Ok::<(), inquire::error::CustomUserError>(())
/// ```
#[derive(Clone)]
pub struct MaxLengthValidator {
    limit: usize,
    message: String,
}

impl MaxLengthValidator {
    /// Create a new instance of this validator, requiring at most the given length, otherwise
    /// returning an error with default message.
    pub fn new(limit: usize) -> Self {
        Self {
            limit,
            message: format!("The length of the response should be at most {}", limit),
        }
    }

    /// Define a custom error message returned by the validator.
    /// Defaults to `The length of the response should be at most $length`.
    pub fn with_message(mut self, message: impl Into<String>) -> Self {
        self.message = message.into();
        self
    }

    fn validate_inquire_length<T: InquireLength>(
        &self,
        input: T,
    ) -> Result<Validation, CustomUserError> {
        Ok(if input.inquire_length() <= self.limit {
            Validation::Valid
        } else {
            Validation::Invalid(self.message.as_str().into())
        })
    }
}

impl StringValidator for MaxLengthValidator {
    fn validate(&self, input: &str) -> Result<Validation, CustomUserError> {
        self.validate_inquire_length(input)
    }
}

impl<T: ?Sized> MultiOptionValidator<T> for MaxLengthValidator {
    fn validate(&self, input: &[ListOption<&T>]) -> Result<Validation, CustomUserError> {
        self.validate_inquire_length(input)
    }
}

/// Shorthand for the built-in [`MaxLengthValidator`] that checks whether the answer length is
/// smaller than or equal to the specified threshold.
///
/// # Arguments
///
/// * `$length` - Maximum length of the input.
/// * `$message` - optional - Error message returned by the validator.
///   Defaults to "The length of the response should be at most $length"
///
/// # Examples
///
/// ```
/// use inquire::{max_length, validator::{StringValidator, Validation}};
///
/// let validator = max_length!(5);
/// assert_eq!(Validation::Valid, validator.validate("Good")?);
/// assert_eq!(Validation::Invalid("The length of the response should be at most 5".into()), validator.validate("Terrible")?);
///
/// let validator = max_length!(5, "Not too large!");
/// assert_eq!(Validation::Valid, validator.validate("Good")?);
/// assert_eq!(Validation::Invalid("Not too large!".into()), validator.validate("Terrible")?);
/// # Ok::<(), inquire::error::CustomUserError>(())
/// ```
#[macro_export]
#[cfg(feature = "macros")]
macro_rules! max_length {
    ($length:expr) => {
        $crate::validator::MaxLengthValidator::new($length)
    };

    ($length:expr, $message:expr) => {
        $crate::max_length!($length).with_message($message)
    };
}

/// Built-in validator that checks whether the answer length is larger than
/// or equal to the specified threshold.
///
/// The validator uses a custom-built length function that
/// has a special implementation for strings which counts the number of
/// graphemes. See this [StackOverflow question](https://stackoverflow.com/questions/46290655/get-the-string-length-in-characters-in-rust).
///
/// # Examples
///
/// ```
/// use inquire::validator::{MinLengthValidator, StringValidator, Validation};
///
/// let validator = MinLengthValidator::new(3);
/// assert_eq!(Validation::Valid, validator.validate("Yes")?);
/// assert_eq!(
///     Validation::Invalid("The length of the response should be at least 3".into()),
///     validator.validate("No")?,
/// );
///
/// let validator = MinLengthValidator::new(3).with_message("You have to give me more than that!");
/// assert_eq!(Validation::Valid, validator.validate("Yes")?);
/// assert_eq!(
///     Validation::Invalid("You have to give me more than that!".into()),
///     validator.validate("No")?,
/// );
/// # Ok::<(), inquire::error::CustomUserError>(())
/// ```
#[derive(Clone)]
pub struct MinLengthValidator {
    limit: usize,
    message: String,
}

impl MinLengthValidator {
    /// Create a new instance of this validator, requiring at least the given length, otherwise
    /// returning an error with default message.
    pub fn new(limit: usize) -> Self {
        Self {
            limit,
            message: format!("The length of the response should be at least {}", limit),
        }
    }

    /// Define a custom error message returned by the validator.
    /// Defaults to `The length of the response should be at least $length`.
    pub fn with_message(mut self, message: impl Into<String>) -> Self {
        self.message = message.into();
        self
    }

    fn validate_inquire_length<T: InquireLength>(
        &self,
        input: T,
    ) -> Result<Validation, CustomUserError> {
        Ok(if input.inquire_length() >= self.limit {
            Validation::Valid
        } else {
            Validation::Invalid(self.message.as_str().into())
        })
    }
}

impl StringValidator for MinLengthValidator {
    fn validate(&self, input: &str) -> Result<Validation, CustomUserError> {
        self.validate_inquire_length(input)
    }
}

impl<T: ?Sized> MultiOptionValidator<T> for MinLengthValidator {
    fn validate(&self, input: &[ListOption<&T>]) -> Result<Validation, CustomUserError> {
        self.validate_inquire_length(input)
    }
}

/// Shorthand for the built-in [`MinLengthValidator`] that checks whether the answer length is
/// larger than or equal to the specified threshold.
///
/// # Arguments
///
/// * `$length` - Minimum length of the input.
/// * `$message` - optional - Error message returned by the validator.
///   Defaults to "The length of the response should be at least $length"
///
/// # Examples
///
/// ```
/// use inquire::{min_length, validator::{StringValidator, Validation}};
///
/// let validator = min_length!(3);
/// assert_eq!(Validation::Valid, validator.validate("Yes")?);
/// assert_eq!(Validation::Invalid("The length of the response should be at least 3".into()), validator.validate("No")?);
///
/// let validator = min_length!(3, "You have to give me more than that!");
/// assert_eq!(Validation::Valid, validator.validate("Yes")?);
/// assert_eq!(Validation::Invalid("You have to give me more than that!".into()), validator.validate("No")?);
/// # Ok::<(), inquire::error::CustomUserError>(())
/// ```
#[macro_export]
#[cfg(feature = "macros")]
macro_rules! min_length {
    ($length:expr) => {
        $crate::validator::MinLengthValidator::new($length)
    };

    ($length:expr, $message:expr) => {
        $crate::min_length!($length).with_message($message)
    };
}

/// Built-in validator that checks whether the answer length is equal to
/// the specified value.
///
/// The validator uses a custom-built length function that
/// has a special implementation for strings which counts the number of
/// graphemes. See this [StackOverflow question](https://stackoverflow.com/questions/46290655/get-the-string-length-in-characters-in-rust).
///
/// # Examples
///
/// ```
/// use inquire::validator::{ExactLengthValidator, StringValidator, Validation};
///
/// let validator = ExactLengthValidator::new(3);
/// assert_eq!(Validation::Valid, validator.validate("Yes")?);
/// assert_eq!(
///     Validation::Invalid("The length of the response should be 3".into()),
///     validator.validate("No")?,
/// );
///
/// let validator = ExactLengthValidator::new(3).with_message("Three characters please.");
/// assert_eq!(Validation::Valid, validator.validate("Yes")?);
/// assert_eq!(Validation::Invalid("Three characters please.".into()), validator.validate("No")?);
/// # Ok::<(), inquire::error::CustomUserError>(())
/// ```
#[derive(Clone)]
pub struct ExactLengthValidator {
    length: usize,
    message: String,
}

impl ExactLengthValidator {
    /// Create a new instance of this validator, requiring exactly the given length, otherwise
    /// returning an error with default message.
    pub fn new(length: usize) -> Self {
        Self {
            length,
            message: format!("The length of the response should be {}", length),
        }
    }

    /// Define a custom error message returned by the validator.
    /// Defaults to `The length of the response should be $length`.
    pub fn with_message(mut self, message: impl Into<String>) -> Self {
        self.message = message.into();
        self
    }

    fn validate_inquire_length<T: InquireLength>(
        &self,
        input: T,
    ) -> Result<Validation, CustomUserError> {
        Ok(if input.inquire_length() == self.length {
            Validation::Valid
        } else {
            Validation::Invalid(self.message.as_str().into())
        })
    }
}

impl StringValidator for ExactLengthValidator {
    fn validate(&self, input: &str) -> Result<Validation, CustomUserError> {
        self.validate_inquire_length(input)
    }
}

impl<T: ?Sized> MultiOptionValidator<T> for ExactLengthValidator {
    fn validate(&self, input: &[ListOption<&T>]) -> Result<Validation, CustomUserError> {
        self.validate_inquire_length(input)
    }
}

/// Shorthand for the built-in [`ExactLengthValidator`] that checks whether the answer length is
/// equal to the specified value.
///
/// # Arguments
///
/// * `$length` - Expected length of the input.
/// * `$message` - optional - Error message returned by the validator.
///   Defaults to "The length of the response should be $length"
///
/// # Examples
///
/// ```
/// use inquire::{length, validator::{StringValidator, Validation}};
///
/// let validator = length!(3);
/// assert_eq!(Validation::Valid, validator.validate("Yes")?);
/// assert_eq!(Validation::Invalid("The length of the response should be 3".into()), validator.validate("No")?);
///
/// let validator = length!(3, "Three characters please.");
/// assert_eq!(Validation::Valid, validator.validate("Yes")?);
/// assert_eq!(Validation::Invalid("Three characters please.".into()), validator.validate("No")?);
/// # Ok::<(), inquire::error::CustomUserError>(())
/// ```
#[macro_export]
#[cfg(feature = "macros")]
macro_rules! length {
    ($length:expr) => {
        $crate::validator::ExactLengthValidator::new($length)
    };

    ($length:expr, $message:expr) => {
        $crate::length!($length).with_message($message)
    };
}

#[cfg(test)]
mod validators_test {
    use crate::{
        error::CustomUserError,
        list_option::ListOption,
        validator::{
            ExactLengthValidator, MaxLengthValidator, MinLengthValidator, MultiOptionValidator,
            StringValidator, Validation,
        },
    };

    fn build_option_vec(len: usize) -> Vec<ListOption<&'static str>> {
        let mut options = Vec::new();

        for i in 0..len {
            options.push(ListOption::new(i, ""));
        }

        options
    }

    #[test]
    fn string_length_counts_graphemes() -> Result<(), CustomUserError> {
        let validator = ExactLengthValidator::new(5);
        let validator: &dyn StringValidator = &validator;

        assert!(matches!(validator.validate("five!")?, Validation::Valid));
        assert!(matches!(validator.validate("♥️♥️♥️♥️♥️")?, Validation::Valid));
        assert!(matches!(
            validator.validate("🤦🏼‍♂️🤦🏼‍♂️🤦🏼‍♂️🤦🏼‍♂️🤦🏼‍♂️")?,
            Validation::Valid
        ));

        assert!(matches!(
            validator.validate("five!!!")?,
            Validation::Invalid(_)
        ));
        assert!(matches!(
            validator.validate("🤦🏼‍♂️🤦🏼‍♂️🤦🏼‍♂️🤦🏼‍♂️")?,
            Validation::Invalid(_)
        ));
        assert!(matches!(
            validator.validate("🤦🏼‍♂️🤦🏼‍♂️🤦🏼‍♂️🤦🏼‍♂️🤦🏼‍♂️🤦🏼‍♂️")?,
            Validation::Invalid(_)
        ));

        Ok(())
    }

    #[test]
    fn slice_length() -> Result<(), CustomUserError> {
        let validator = ExactLengthValidator::new(5);
        let validator: &dyn MultiOptionValidator<str> = &validator;

        assert!(matches!(
            validator.validate(&build_option_vec(5))?,
            Validation::Valid
        ));
        assert!(matches!(
            validator.validate(&build_option_vec(4))?,
            Validation::Invalid(_)
        ));
        assert!(matches!(
            validator.validate(&build_option_vec(6))?,
            Validation::Invalid(_)
        ));

        Ok(())
    }

    #[test]
    fn string_max_length_counts_graphemes() -> Result<(), CustomUserError> {
        let validator = MaxLengthValidator::new(5);
        let validator: &dyn StringValidator = &validator;

        assert!(matches!(validator.validate("")?, Validation::Valid));
        assert!(matches!(validator.validate("five!")?, Validation::Valid));
        assert!(matches!(validator.validate("♥️♥️♥️♥️♥️")?, Validation::Valid));
        assert!(matches!(
            validator.validate("🤦🏼‍♂️🤦🏼‍♂️🤦🏼‍♂️🤦🏼‍♂️🤦🏼‍♂️")?,
            Validation::Valid
        ));

        assert!(matches!(
            validator.validate("five!!!")?,
            Validation::Invalid(_)
        ));
        assert!(matches!(
            validator.validate("♥️♥️♥️♥️♥️♥️")?,
            Validation::Invalid(_)
        ));
        assert!(matches!(
            validator.validate("🤦🏼‍♂️🤦🏼‍♂️🤦🏼‍♂️🤦🏼‍♂️🤦🏼‍♂️🤦🏼‍♂️")?,
            Validation::Invalid(_)
        ));

        Ok(())
    }

    #[test]
    fn slice_max_length() -> Result<(), CustomUserError> {
        let validator = MaxLengthValidator::new(5);
        let validator: &dyn MultiOptionValidator<str> = &validator;

        assert!(matches!(
            validator.validate(&build_option_vec(0))?,
            Validation::Valid
        ));
        assert!(matches!(
            validator.validate(&build_option_vec(1))?,
            Validation::Valid
        ));
        assert!(matches!(
            validator.validate(&build_option_vec(2))?,
            Validation::Valid
        ));
        assert!(matches!(
            validator.validate(&build_option_vec(3))?,
            Validation::Valid
        ));
        assert!(matches!(
            validator.validate(&build_option_vec(4))?,
            Validation::Valid
        ));
        assert!(matches!(
            validator.validate(&build_option_vec(5))?,
            Validation::Valid
        ));
        assert!(matches!(
            validator.validate(&build_option_vec(6))?,
            Validation::Invalid(_)
        ));
        assert!(matches!(
            validator.validate(&build_option_vec(7))?,
            Validation::Invalid(_)
        ));
        assert!(matches!(
            validator.validate(&build_option_vec(8))?,
            Validation::Invalid(_)
        ));

        Ok(())
    }

    #[test]
    fn string_min_length_counts_graphemes() -> Result<(), CustomUserError> {
        let validator = MinLengthValidator::new(5);
        let validator: &dyn StringValidator = &validator;

        assert!(matches!(validator.validate("")?, Validation::Invalid(_)));
        assert!(matches!(
            validator.validate("♥️♥️♥️♥️")?,
            Validation::Invalid(_)
        ));
        assert!(matches!(
            validator.validate("mike")?,
            Validation::Invalid(_)
        ));

        assert!(matches!(validator.validate("five!")?, Validation::Valid));
        assert!(matches!(validator.validate("five!!!")?, Validation::Valid));
        assert!(matches!(validator.validate("♥️♥️♥️♥️♥️")?, Validation::Valid));
        assert!(matches!(validator.validate("♥️♥️♥️♥️♥️♥️")?, Validation::Valid));
        assert!(matches!(
            validator.validate("🤦🏼‍♂️🤦🏼‍♂️🤦🏼‍♂️🤦🏼‍♂️🤦🏼‍♂️")?,
            Validation::Valid
        ));
        assert!(matches!(
            validator.validate("🤦🏼‍♂️🤦🏼‍♂️🤦🏼‍♂️🤦🏼‍♂️🤦🏼‍♂️🤦🏼‍♂️")?,
            Validation::Valid
        ));

        Ok(())
    }

    #[test]
    fn slice_min_length() -> Result<(), CustomUserError> {
        let validator = MinLengthValidator::new(5);
        let validator: &dyn MultiOptionValidator<str> = &validator;

        assert!(matches!(
            validator.validate(&build_option_vec(0))?,
            Validation::Invalid(_)
        ));
        assert!(matches!(
            validator.validate(&build_option_vec(1))?,
            Validation::Invalid(_)
        ));
        assert!(matches!(
            validator.validate(&build_option_vec(2))?,
            Validation::Invalid(_)
        ));
        assert!(matches!(
            validator.validate(&build_option_vec(3))?,
            Validation::Invalid(_)
        ));
        assert!(matches!(
            validator.validate(&build_option_vec(4))?,
            Validation::Invalid(_)
        ));
        assert!(matches!(
            validator.validate(&build_option_vec(5))?,
            Validation::Valid
        ));
        assert!(matches!(
            validator.validate(&build_option_vec(6))?,
            Validation::Valid
        ));
        assert!(matches!(
            validator.validate(&build_option_vec(7))?,
            Validation::Valid
        ));
        assert!(matches!(
            validator.validate(&build_option_vec(8))?,
            Validation::Valid
        ));

        Ok(())
    }
}