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
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
use crate::isl::isl_import::IslImportType;
use crate::isl::isl_range::{Range, RangeType};
use crate::isl::isl_type_reference::IslTypeRefImpl;
use crate::isl::util::{Annotation, TimestampOffset, ValidValue};
use crate::isl::IslVersion;
use crate::result::{
    invalid_schema_error, invalid_schema_error_raw, IonSchemaError, IonSchemaResult,
};
use ion_rs::element::Element;
use ion_rs::IonType;
use std::collections::HashMap;
use std::convert::{TryFrom, TryInto};

/// Provides public facing APIs for constructing ISL constraints programmatically for ISL 1.0
pub mod v_1_0 {
    use crate::isl::isl_constraint::{
        IslAnnotationsConstraint, IslConstraint, IslConstraintImpl, IslRegexConstraint,
        IslTimestampOffsetConstraint, IslValidValuesConstraint,
    };
    use crate::isl::isl_range::{IntegerRange, NonNegativeIntegerRange, Range, RangeImpl};
    use crate::isl::isl_type_reference::IslTypeRef;
    use crate::isl::util::{Annotation, TimestampOffset, TimestampPrecision, ValidValue};
    use crate::isl::IslVersion;
    use crate::result::IonSchemaResult;
    use ion_rs::element::Element;

    /// Creates a `type` constraint using the [IslTypeRef] referenced inside it
    // type is rust keyword hence this method is named type_constraint unlike other ISL constraint methods
    pub fn type_constraint(isl_type: IslTypeRef) -> IslConstraint {
        IslConstraint::new(
            IslVersion::V1_0,
            IslConstraintImpl::Type(isl_type.type_reference),
        )
    }

    /// Creates an `all_of` constraint using the [IslTypeRef] referenced inside it
    pub fn all_of<A: Into<Vec<IslTypeRef>>>(isl_types: A) -> IslConstraint {
        IslConstraint::new(
            IslVersion::V1_0,
            IslConstraintImpl::AllOf(
                isl_types
                    .into()
                    .into_iter()
                    .map(|t| t.type_reference)
                    .collect(),
            ),
        )
    }

    /// Creates an `any_of` constraint using the [IslTypeRef] referenced inside it
    pub fn any_of<A: Into<Vec<IslTypeRef>>>(isl_types: A) -> IslConstraint {
        IslConstraint::new(
            IslVersion::V1_0,
            IslConstraintImpl::AnyOf(
                isl_types
                    .into()
                    .into_iter()
                    .map(|t| t.type_reference)
                    .collect(),
            ),
        )
    }

    /// Creates a `one_of` constraint using the [IslTypeRef] referenced inside it
    pub fn one_of<A: Into<Vec<IslTypeRef>>>(isl_types: A) -> IslConstraint {
        IslConstraint::new(
            IslVersion::V1_0,
            IslConstraintImpl::OneOf(
                isl_types
                    .into()
                    .into_iter()
                    .map(|t| t.type_reference)
                    .collect(),
            ),
        )
    }

    /// Creates an `ordered_elements` constraint using the [IslTypeRef] referenced inside it
    pub fn ordered_elements<A: Into<Vec<IslTypeRef>>>(isl_types: A) -> IslConstraint {
        IslConstraint::new(
            IslVersion::V1_0,
            IslConstraintImpl::OrderedElements(
                isl_types
                    .into()
                    .into_iter()
                    .map(|t| t.type_reference)
                    .collect(),
            ),
        )
    }

    /// Creates a `precision` constraint using the range specified in it
    pub fn precision(precision: NonNegativeIntegerRange) -> IslConstraint {
        IslConstraint::new(
            IslVersion::V1_0,
            IslConstraintImpl::Precision(Range::NonNegativeInteger(precision)),
        )
    }

    /// Creates a `scale` constraint using the range specified in it
    pub fn scale(scale: IntegerRange) -> IslConstraint {
        IslConstraint::new(
            IslVersion::V1_0,
            IslConstraintImpl::Scale(Range::Integer(scale)),
        )
    }

    /// Creates a `fields` constraint using the field names and [IslTypeRef]s referenced inside it
    pub fn fields<I>(fields: I) -> IslConstraint
    where
        I: Iterator<Item = (String, IslTypeRef)>,
    {
        IslConstraint::new(
            IslVersion::V1_0,
            IslConstraintImpl::Fields(fields.map(|(s, t)| (s, t.type_reference)).collect(), false),
        )
    }

    /// Creates a `not` constraint using the [IslTypeRef] referenced inside it
    pub fn not(isl_type: IslTypeRef) -> IslConstraint {
        IslConstraint::new(
            IslVersion::V1_0,
            IslConstraintImpl::Not(isl_type.type_reference),
        )
    }

    /// Creates a `contains` constraint using the [Element] specified inside it
    pub fn contains<A: Into<Vec<Element>>>(values: A) -> IslConstraint {
        IslConstraint::new(IslVersion::V1_0, IslConstraintImpl::Contains(values.into()))
    }

    /// Creates a `container_length` constraint using the range specified in it
    pub fn container_length(length: NonNegativeIntegerRange) -> IslConstraint {
        IslConstraint::new(
            IslVersion::V1_0,
            IslConstraintImpl::ContainerLength(Range::NonNegativeInteger(length)),
        )
    }

    /// Creates a `byte_length` constraint using the range specified in it
    pub fn byte_length(length: RangeImpl<usize>) -> IslConstraint {
        IslConstraint::new(
            IslVersion::V1_0,
            IslConstraintImpl::ByteLength(Range::NonNegativeInteger(length)),
        )
    }

    /// Creates a `codepoint_length` constraint using the range specified in it
    pub fn codepoint_length(length: RangeImpl<usize>) -> IslConstraint {
        IslConstraint::new(
            IslVersion::V1_0,
            IslConstraintImpl::CodepointLength(Range::NonNegativeInteger(length)),
        )
    }

    /// Creates a `timestamp_precision` constraint using the range specified in it
    pub fn timestamp_precision(precision: RangeImpl<TimestampPrecision>) -> IslConstraint {
        IslConstraint::new(
            IslVersion::V1_0,
            IslConstraintImpl::TimestampPrecision(Range::TimestampPrecision(precision)),
        )
    }

    /// Creates a `timestamp_offset` constraint using the offset list specified in it
    pub fn timestamp_offset(offsets: Vec<TimestampOffset>) -> IslConstraint {
        IslConstraint::new(
            IslVersion::V1_0,
            IslConstraintImpl::TimestampOffset(IslTimestampOffsetConstraint::new(offsets)),
        )
    }

    /// Creates an `utf_byte_length` constraint using the range specified in it
    pub fn utf8_byte_length(length: NonNegativeIntegerRange) -> IslConstraint {
        IslConstraint::new(
            IslVersion::V1_0,
            IslConstraintImpl::Utf8ByteLength(Range::NonNegativeInteger(length)),
        )
    }

    /// Creates an `element` constraint using the [IslTypeRef] referenced inside it
    pub fn element(isl_type: IslTypeRef) -> IslConstraint {
        IslConstraint::new(
            IslVersion::V1_0,
            IslConstraintImpl::Element(isl_type.type_reference, false),
        )
    }

    /// Creates an `annotations` constraint using [str]s and [Element]s specified inside it
    pub fn annotations<'a, A: IntoIterator<Item = &'a str>, B: IntoIterator<Item = Element>>(
        annotations_modifiers: A,
        annotations: B,
    ) -> IslConstraint {
        let annotations_modifiers: Vec<&str> = annotations_modifiers.into_iter().collect();
        let annotations: Vec<Annotation> = annotations
            .into_iter()
            .map(|a| {
                Annotation::new(
                    a.as_text().unwrap().to_owned(),
                    Annotation::is_annotation_required(
                        &a,
                        annotations_modifiers.contains(&"required"),
                    ),
                )
            })
            .collect();
        IslConstraint::new(
            IslVersion::V1_0,
            IslConstraintImpl::Annotations(IslAnnotationsConstraint::new(
                annotations_modifiers.contains(&"closed"),
                annotations_modifiers.contains(&"ordered"),
                annotations,
            )),
        )
    }

    /// Creates a `valid_values` constraint using the [Element]s specified inside it
    pub fn valid_values_with_values(values: Vec<Element>) -> IonSchemaResult<IslConstraint> {
        let valid_values: IonSchemaResult<Vec<ValidValue>> =
            values.iter().map(|e| e.try_into()).collect();
        Ok(IslConstraint::new(
            IslVersion::V1_0,
            IslConstraintImpl::ValidValues(IslValidValuesConstraint {
                valid_values: valid_values?,
            }),
        ))
    }

    /// Creates a `valid_values` constraint using the [Range] specified inside it
    pub fn valid_values_with_range(range: Range) -> IslConstraint {
        IslConstraint::new(
            IslVersion::V1_0,
            IslConstraintImpl::ValidValues(IslValidValuesConstraint {
                valid_values: vec![ValidValue::Range(range)],
            }),
        )
    }

    /// Creates a `regex` constraint using the expression and flags (case_insensitive, multi_line)
    pub fn regex(case_insensitive: bool, multi_line: bool, expression: String) -> IslConstraint {
        IslConstraint::new(
            IslVersion::V1_0,
            IslConstraintImpl::Regex(IslRegexConstraint::new(
                case_insensitive,
                multi_line,
                expression,
            )),
        )
    }
}

/// Provides public facing APIs for constructing ISL constraints programmatically for ISL 2.0
pub mod v_2_0 {
    use crate::isl::isl_constraint::IslConstraint;
    use crate::isl::isl_constraint::{
        IslConstraintImpl, IslTimestampOffsetConstraint, IslValidValuesConstraint,
    };
    use crate::isl::isl_range::{NonNegativeIntegerRange, Range, RangeImpl};
    use crate::isl::isl_type_reference::IslTypeRef;
    use crate::isl::util::{TimestampOffset, TimestampPrecision, ValidValue};
    use crate::isl::IslVersion;
    use crate::result::IonSchemaResult;
    use ion_rs::element::Element;
    use ion_rs::Int;

    /// Creates a `type` constraint using the [IslTypeRef] referenced inside it
    // type is rust keyword hence this method is named type_constraint unlike other ISL constraint methods
    pub fn type_constraint(isl_type: IslTypeRef) -> IslConstraint {
        IslConstraint::new(
            IslVersion::V2_0,
            IslConstraintImpl::Type(isl_type.type_reference),
        )
    }

    /// Creates an `all_of` constraint using the [IslTypeRef] referenced inside it
    pub fn all_of<A: Into<Vec<IslTypeRef>>>(isl_types: A) -> IslConstraint {
        IslConstraint::new(
            IslVersion::V2_0,
            IslConstraintImpl::AllOf(
                isl_types
                    .into()
                    .into_iter()
                    .map(|t| t.type_reference)
                    .collect(),
            ),
        )
    }

    /// Creates an `any_of` constraint using the [IslTypeRef] referenced inside it
    pub fn any_of<A: Into<Vec<IslTypeRef>>>(isl_types: A) -> IslConstraint {
        IslConstraint::new(
            IslVersion::V2_0,
            IslConstraintImpl::AnyOf(
                isl_types
                    .into()
                    .into_iter()
                    .map(|t| t.type_reference)
                    .collect(),
            ),
        )
    }

    /// Creates an `one_of` constraint using the [IslTypeRef] referenced inside it
    pub fn one_of<A: Into<Vec<IslTypeRef>>>(isl_types: A) -> IslConstraint {
        IslConstraint::new(
            IslVersion::V2_0,
            IslConstraintImpl::OneOf(
                isl_types
                    .into()
                    .into_iter()
                    .map(|t| t.type_reference)
                    .collect(),
            ),
        )
    }

    /// Creates an `ordered_elements` constraint using the [IslTypeRef] referenced inside it
    pub fn ordered_elements<A: Into<Vec<IslTypeRef>>>(isl_types: A) -> IslConstraint {
        IslConstraint::new(
            IslVersion::V2_0,
            IslConstraintImpl::OrderedElements(
                isl_types
                    .into()
                    .into_iter()
                    .map(|t| t.type_reference)
                    .collect(),
            ),
        )
    }

    /// Creates a `precision` constraint using the range specified in it
    pub fn precision(precision: NonNegativeIntegerRange) -> IslConstraint {
        IslConstraint::new(
            IslVersion::V2_0,
            IslConstraintImpl::Precision(Range::NonNegativeInteger(precision)),
        )
    }

    /// Creates an `exponent` constraint from a [Range] specifying an exponent range.
    pub fn exponent(exponent: RangeImpl<Int>) -> IslConstraint {
        IslConstraint::new(
            IslVersion::V2_0,
            IslConstraintImpl::Exponent(Range::Integer(exponent)),
        )
    }

    /// Creates a `fields` constraint using the field names and [IslTypeRef]s referenced inside it
    pub fn fields<I>(fields: I) -> IslConstraint
    where
        I: Iterator<Item = (String, IslTypeRef)>,
    {
        IslConstraint::new(
            IslVersion::V2_0,
            IslConstraintImpl::Fields(fields.map(|(s, t)| (s, t.type_reference)).collect(), false),
        )
    }

    /// Creates a `field_names` constraint using the [IslTypeRef] referenced inside it and considers whether distinct elements are required or not
    pub fn field_names(isl_type: IslTypeRef, require_distinct_field_names: bool) -> IslConstraint {
        IslConstraint::new(
            IslVersion::V2_0,
            IslConstraintImpl::FieldNames(isl_type.type_reference, require_distinct_field_names),
        )
    }

    /// Creates a `not` constraint using the [IslTypeRef] referenced inside it
    pub fn not(isl_type: IslTypeRef) -> IslConstraint {
        IslConstraint::new(
            IslVersion::V2_0,
            IslConstraintImpl::Not(isl_type.type_reference),
        )
    }

    /// Creates a `contains` constraint using the [Element] specified inside it
    pub fn contains<A: Into<Vec<Element>>>(values: A) -> IslConstraint {
        IslConstraint::new(IslVersion::V2_0, IslConstraintImpl::Contains(values.into()))
    }

    /// Creates a `container_length` constraint using the range specified in it
    pub fn container_length(length: NonNegativeIntegerRange) -> IslConstraint {
        IslConstraint::new(
            IslVersion::V2_0,
            IslConstraintImpl::ContainerLength(Range::NonNegativeInteger(length)),
        )
    }

    /// Creates a `byte_length` constraint using the range specified in it
    pub fn byte_length(length: RangeImpl<usize>) -> IslConstraint {
        IslConstraint::new(
            IslVersion::V2_0,
            IslConstraintImpl::ByteLength(Range::NonNegativeInteger(length)),
        )
    }

    /// Creates a `codepoint_length` constraint using the range specified in it
    pub fn codepoint_length(length: RangeImpl<usize>) -> IslConstraint {
        IslConstraint::new(
            IslVersion::V2_0,
            IslConstraintImpl::CodepointLength(Range::NonNegativeInteger(length)),
        )
    }

    /// Creates a `timestamp_precision` constraint using the range specified in it
    pub fn timestamp_precision(precision: RangeImpl<TimestampPrecision>) -> IslConstraint {
        IslConstraint::new(
            IslVersion::V2_0,
            IslConstraintImpl::TimestampPrecision(Range::TimestampPrecision(precision)),
        )
    }

    /// Creates a `timestamp_offset` constraint using the offset list specified in it
    pub fn timestamp_offset(offsets: Vec<TimestampOffset>) -> IslConstraint {
        IslConstraint::new(
            IslVersion::V2_0,
            IslConstraintImpl::TimestampOffset(IslTimestampOffsetConstraint::new(offsets)),
        )
    }

    /// Creates a `utf8_byte_length` constraint using the range specified in it
    pub fn utf8_byte_length(length: NonNegativeIntegerRange) -> IslConstraint {
        IslConstraint::new(
            IslVersion::V2_0,
            IslConstraintImpl::Utf8ByteLength(Range::NonNegativeInteger(length)),
        )
    }

    /// Creates an `element` constraint using the [IslTypeRef] referenced inside it and considers whether distinct elements are required or not
    pub fn element(isl_type: IslTypeRef, require_distinct_elements: bool) -> IslConstraint {
        IslConstraint::new(
            IslVersion::V2_0,
            IslConstraintImpl::Element(isl_type.type_reference, require_distinct_elements),
        )
    }

    /// Creates an `annotations` constraint using [str]s and [Element]s specified inside it
    pub fn annotations<'a, A: IntoIterator<Item = &'a str>, B: IntoIterator<Item = Element>>(
        annotations_modifiers: A,
        annotations: B,
    ) -> IslConstraint {
        todo!()
    }

    /// Creates a `valid_values` constraint using the [Element]s specified inside it
    pub fn valid_values_with_values(values: Vec<Element>) -> IonSchemaResult<IslConstraint> {
        let valid_values: IonSchemaResult<Vec<ValidValue>> =
            values.iter().map(|e| e.try_into()).collect();
        Ok(IslConstraint::new(
            IslVersion::V2_0,
            IslConstraintImpl::ValidValues(IslValidValuesConstraint {
                valid_values: valid_values?,
            }),
        ))
    }

    /// Creates a `valid_values` constraint using the [Range] specified inside it
    pub fn valid_values_with_range(range: Range) -> IslConstraint {
        IslConstraint::new(
            IslVersion::V2_0,
            IslConstraintImpl::ValidValues(IslValidValuesConstraint {
                valid_values: vec![ValidValue::Range(range)],
            }),
        )
    }

    /// Creates a `regex` constraint using the expression and flags (case_insensitive, multi_line)
    pub fn regex(case_insensitive: bool, multi_line: bool, expression: String) -> IslConstraint {
        todo!()
    }
}

/// Represents schema constraints [IslConstraint]
#[derive(Debug, Clone, PartialEq)]
pub struct IslConstraint {
    pub(crate) version: IslVersion,
    pub(crate) constraint: IslConstraintImpl,
}

impl IslConstraint {
    pub(crate) fn new(version: IslVersion, constraint: IslConstraintImpl) -> Self {
        Self {
            constraint,
            version,
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub(crate) enum IslConstraintImpl {
    AllOf(Vec<IslTypeRefImpl>),
    Annotations(IslAnnotationsConstraint),
    AnyOf(Vec<IslTypeRefImpl>),
    ByteLength(Range),
    CodepointLength(Range),
    Contains(Vec<Element>),
    ContentClosed,
    ContainerLength(Range),
    // Represents Element(type_reference, expected_distinct).
    // For ISL 2.0 true/false is specified based on whether `distinct` annotation is present or not.
    // For ISL 1.0 which doesn't support `distinct` elements this will be (type_reference, false).
    Element(IslTypeRefImpl, bool),
    Exponent(Range),
    // Represents Fields(fields, content_closed)
    // For ISL 2.0 true/false is specified based on whether `closed::` annotation is present or not
    // For ISL 1.0 this will always be (fields, false) as it doesn't support `closed::` annotation on fields constraint
    Fields(HashMap<String, IslTypeRefImpl>, bool),
    // Represents FieldNames(type_reference, expected_distinct).
    // For ISL 2.0 true/false is specified based on whether `distinct` annotation is present or not.
    // For ISL 1.0 which doesn't support `field_names` constraint this will be (type_reference, false).
    FieldNames(IslTypeRefImpl, bool),
    Not(IslTypeRefImpl),
    Occurs(Range),
    OneOf(Vec<IslTypeRefImpl>),
    OrderedElements(Vec<IslTypeRefImpl>),
    Precision(Range),
    Regex(IslRegexConstraint),
    Scale(Range),
    TimestampOffset(IslTimestampOffsetConstraint),
    TimestampPrecision(Range),
    Type(IslTypeRefImpl),
    Unknown(String, Element), // Unknown constraint is used to store open contents
    Utf8ByteLength(Range),
    ValidValues(IslValidValuesConstraint),
}

impl IslConstraintImpl {
    /// Parse constraints inside an [Element] to an [IslConstraint]
    pub fn from_ion_element(
        isl_version: IslVersion,
        constraint_name: &str,
        value: &Element,
        type_name: &str,
        inline_imported_types: &mut Vec<IslImportType>,
    ) -> IonSchemaResult<IslConstraintImpl> {
        // TODO: add more constraints to match below
        match constraint_name {
            "all_of" => {
                let types: Vec<IslTypeRefImpl> =
                    IslConstraintImpl::isl_type_references_from_ion_element(
                        isl_version,
                        value,
                        inline_imported_types,
                        "all_of",
                    )?;
                Ok(IslConstraintImpl::AllOf(types))
            }
            "annotations" => {
                if value.is_null() {
                    return invalid_schema_error(
                        "annotations constraint was a null instead of a list",
                    );
                }

                if value.ion_type() != IonType::List {
                    return invalid_schema_error(format!(
                        "annotations constraint was a {:?} instead of a list",
                        value.ion_type()
                    ));
                }

                Ok(IslConstraintImpl::Annotations(value.try_into()?))
            }
            "any_of" => {
                let types: Vec<IslTypeRefImpl> =
                    IslConstraintImpl::isl_type_references_from_ion_element(
                        isl_version,
                        value,
                        inline_imported_types,
                        "any_of",
                    )?;
                Ok(IslConstraintImpl::AnyOf(types))
            }
            "byte_length" => Ok(IslConstraintImpl::ByteLength(Range::from_ion_element(
                value,
                RangeType::NonNegativeInteger,
            )?)),
            "codepoint_length" => Ok(IslConstraintImpl::CodepointLength(Range::from_ion_element(
                value,
                RangeType::NonNegativeInteger,
            )?)),
            "contains" => {
                if value.is_null() {
                    return invalid_schema_error(
                        "contains constraint was a null instead of a list",
                    );
                }

                if value.ion_type() != IonType::List {
                    return invalid_schema_error(format!(
                        "contains constraint was a {:?} instead of a list",
                        value.ion_type()
                    ));
                }

                let values: Vec<Element> = value
                    .as_sequence()
                    .unwrap()
                    .elements()
                    .map(|e| e.to_owned())
                    .collect();
                Ok(IslConstraintImpl::Contains(values))
            }
            "content" => {
                if value.is_null() {
                    return invalid_schema_error(
                        "content constraint was a null instead of a symbol `closed`",
                    );
                }

                if value.ion_type() != IonType::Symbol {
                    return invalid_schema_error(format!(
                        "content constraint was a {:?} instead of a symbol `closed`",
                        value.ion_type()
                    ));
                }

                if let Some(closed) = value.as_text() {
                    if closed != "closed" {
                        return invalid_schema_error(format!(
                            "content constraint was a {closed} instead of a symbol `closed`"
                        ));
                    }
                }

                Ok(IslConstraintImpl::ContentClosed)
            }

            "container_length" => Ok(IslConstraintImpl::ContainerLength(Range::from_ion_element(
                value,
                RangeType::NonNegativeInteger,
            )?)),
            "element" => {
                let type_reference: IslTypeRefImpl =
                    IslTypeRefImpl::from_ion_element(isl_version, value, inline_imported_types)?;
                match isl_version {
                    IslVersion::V1_0 => {
                        // for ISL 1.0 `distinct annotation on `element` constraint is not supported which is represented by `false` here
                        Ok(IslConstraintImpl::Element(type_reference, false))
                    }
                    IslVersion::V2_0 => {
                        // return error if there are any annotations other than `distinct` or `$null_or`
                        if value
                            .annotations()
                            .iter()
                            .any(|a| a.text() != Some("distinct") && a.text() != Some("$null_or"))
                        {
                            return invalid_schema_error(
                                "element constraint can only contain `distinct` annotation",
                            );
                        }

                        // verify whether `distinct`annotation is present or not
                        let require_distinct = value.annotations().contains("distinct");

                        // return error if the type reference contains `occurs` constraint
                        if type_reference.get_occurs_range().is_some() {
                            return invalid_schema_error(
                                "element constraint can not contain type references that contain `occurs` constraint",
                            );
                        }

                        Ok(IslConstraintImpl::Element(type_reference, require_distinct))
                    }
                }
            }
            "field_names" => {
                let type_reference =
                    IslTypeRefImpl::from_ion_element(isl_version, value, inline_imported_types)?;
                match isl_version {
                    IslVersion::V1_0 => {
                        // for ISL 1.0 `field_names` constraint does not exist hence `field_names` will be considered as open content
                        Ok(IslConstraintImpl::Unknown(
                            constraint_name.to_string(),
                            value.to_owned(),
                        ))
                    }
                    IslVersion::V2_0 => {
                        // return error if there are any annotations other than `distinct`
                        if value.annotations().len() > 1
                            || value
                                .annotations()
                                .iter()
                                .any(|a| a.text() != Some("distinct"))
                        {
                            return invalid_schema_error(
                                "field_names constraint can only contain `distinct` annotation",
                            );
                        }

                        // return error if the type reference contains `occurs` constraint
                        if type_reference.get_occurs_range().is_some() {
                            return invalid_schema_error(
                                "field_names constraint can not contain type references that contain `occurs` constraint",
                            );
                        }

                        Ok(IslConstraintImpl::FieldNames(
                            type_reference,
                            value.annotations().contains("distinct"),
                        ))
                    }
                }
            }
            "fields" => {
                let fields: HashMap<String, IslTypeRefImpl> =
                    IslConstraintImpl::isl_fields_from_ion_element(
                        isl_version,
                        value,
                        inline_imported_types,
                    )?;

                if fields.is_empty() {
                    return invalid_schema_error("fields constraint can not be empty");
                }
                match isl_version {
                    IslVersion::V1_0 => Ok(IslConstraintImpl::Fields(fields, false)),
                    IslVersion::V2_0 => {
                        if value.annotations().len() > 1
                            || value
                                .annotations()
                                .iter()
                                .any(|a| a.text() != Some("closed"))
                        {
                            return invalid_schema_error(
                                "fields constraint may only be annotated with 'closed'",
                            );
                        }
                        Ok(IslConstraintImpl::Fields(
                            fields,
                            value.annotations().contains("closed"),
                        ))
                    }
                }
            }
            "one_of" => {
                let types: Vec<IslTypeRefImpl> =
                    IslConstraintImpl::isl_type_references_from_ion_element(
                        isl_version,
                        value,
                        inline_imported_types,
                        "one_of",
                    )?;
                Ok(IslConstraintImpl::OneOf(types))
            }
            "not" => {
                let type_reference: IslTypeRefImpl =
                    IslTypeRefImpl::from_ion_element(isl_version, value, inline_imported_types)?;
                Ok(IslConstraintImpl::Not(type_reference))
            }
            "type" => {
                let type_reference: IslTypeRefImpl =
                    IslTypeRefImpl::from_ion_element(isl_version, value, inline_imported_types)?;
                Ok(IslConstraintImpl::Type(type_reference))
            }
            "occurs" => {
                use IonType::*;
                if value.is_null() {
                    return invalid_schema_error(
                        "expected an integer or integer range for an `occurs` constraint, found null",
                    );
                }
                let range = match value.ion_type() {
                    Symbol => {
                        let sym = try_to!(try_to!(value.as_symbol()).text());
                        match sym {
                            "optional" => Range::optional(),
                            "required" => Range::required(),
                            _ => {
                                return invalid_schema_error(format!(
                                    "only optional and required symbols are supported with occurs constraint, found {sym}"
                                ))
                            }
                        }
                    }
                    List | Int => {
                        if value.ion_type() == Int
                            && value.as_int().unwrap() <= &ion_rs::Int::I64(0)
                        {
                            return invalid_schema_error("occurs constraint can not be 0");
                        }
                        Range::from_ion_element(value, RangeType::NonNegativeInteger)?
                    }
                    _ => {
                        return invalid_schema_error(format!(
                            "ion type: {:?} is not supported with occurs constraint",
                            value.ion_type()
                        ))
                    }
                };
                Ok(IslConstraintImpl::Occurs(range))
            }
            "ordered_elements" => {
                let types: Vec<IslTypeRefImpl> =
                    IslConstraintImpl::isl_type_references_from_ion_element(
                        isl_version,
                        value,
                        inline_imported_types,
                        "ordered_elements",
                    )?;
                Ok(IslConstraintImpl::OrderedElements(types))
            }
            "precision" => Ok(IslConstraintImpl::Precision(Range::from_ion_element(
                value,
                RangeType::Precision,
            )?)),
            "regex" => {
                let case_insensitive = value.annotations().contains("i");
                let multi_line = value.annotations().contains("m");

                let expression = value.as_string().ok_or_else(|| {
                    invalid_schema_error_raw(format!(
                        "expected regex to contain a string expression but found: {}",
                        value.ion_type()
                    ))
                })?;

                Ok(IslConstraintImpl::Regex(IslRegexConstraint::new(
                    case_insensitive,
                    multi_line,
                    expression.to_string(),
                )))
            }
            "scale" => match isl_version {
                IslVersion::V1_0 => Ok(IslConstraintImpl::Scale(Range::from_ion_element(
                    value,
                    RangeType::Any,
                )?)),
                IslVersion::V2_0 => {
                    // for ISL 2.0 scale constraint does not exist hence `scale` will be considered as open content
                    Ok(IslConstraintImpl::Unknown(
                        constraint_name.to_string(),
                        value.to_owned(),
                    ))
                }
            },
            "timestamp_precision" => Ok(IslConstraintImpl::TimestampPrecision(
                Range::from_ion_element(value, RangeType::TimestampPrecision)?,
            )),
            "exponent" => match isl_version {
                IslVersion::V1_0 => {
                    // for ISL 1.0 exponent constraint does not exist hence `exponent` will be considered as open content
                    Ok(IslConstraintImpl::Unknown(
                        constraint_name.to_string(),
                        value.to_owned(),
                    ))
                }
                IslVersion::V2_0 => Ok(IslConstraintImpl::Exponent(Range::from_ion_element(
                    value,
                    RangeType::Any,
                )?)),
            },
            "timestamp_offset" => {
                use IonType::*;
                if value.is_null() {
                    return invalid_schema_error(
                        "expected a list of valid offsets for an `timestamp_offset` constraint, found null",
                    );
                }

                if !value.annotations().is_empty() {
                    return invalid_schema_error("`timestamp_offset` list may not be annotated");
                }

                let valid_offsets: Vec<TimestampOffset> = match value.ion_type() {
                    List => {
                        let list_values = value.as_sequence().unwrap();
                        if list_values.is_empty() {
                            return invalid_schema_error(
                                "`timestamp_offset` constraint must contain at least one offset",
                            );
                        }
                        let list_vec: IonSchemaResult<Vec<TimestampOffset>> = list_values
                            .elements()
                            .map(|e| {
                                if e.is_null() {
                                    return invalid_schema_error(
                                    "`timestamp_offset` values must be non-null strings, found null"
                                );
                                }

                                if e.ion_type() != IonType::String {
                                    return invalid_schema_error(format!(
                                    "`timestamp_offset` values must be non-null strings, found {e}"
                                ));
                                }

                                if !e.annotations().is_empty() {
                                    return invalid_schema_error(format!(
                                        "`timestamp_offset` values may not be annotated, found {e}"
                                    ));
                                }

                                // unwrap here will not panic as we have already verified the ion type to be a string
                                let string_value = e.as_string().unwrap();

                                // convert the string to TimestampOffset which stores offset in minutes
                                string_value.try_into()
                            })
                            .collect();
                        list_vec?
                    }
                    _ => {
                        return invalid_schema_error(format!(
                        "`timestamp_offset` requires a list of offset strings, but found: {value}"
                    ))
                    }
                };
                Ok(IslConstraintImpl::TimestampOffset(
                    IslTimestampOffsetConstraint::new(valid_offsets),
                ))
            }
            "utf8_byte_length" => Ok(IslConstraintImpl::Utf8ByteLength(Range::from_ion_element(
                value,
                RangeType::NonNegativeInteger,
            )?)),
            "valid_values" => Ok(IslConstraintImpl::ValidValues(value.try_into()?)),
            _ => Ok(IslConstraintImpl::Unknown(
                constraint_name.to_string(),
                value.to_owned(),
            )),
        }
    }

    // helper method for from_ion_element to get isl type references from given ion element
    fn isl_type_references_from_ion_element(
        isl_version: IslVersion,
        value: &Element,
        inline_imported_types: &mut Vec<IslImportType>,
        constraint_name: &str,
    ) -> IonSchemaResult<Vec<IslTypeRefImpl>> {
        //TODO: create a method/macro for this ion type check which can be reused
        if value.is_null() {
            return invalid_schema_error(format!(
                "{constraint_name} constraint was a null instead of a list"
            ));
        }
        if value.ion_type() != IonType::List {
            return invalid_schema_error(format!(
                "{} constraint was a {:?} instead of a list",
                constraint_name,
                value.ion_type()
            ));
        }
        value
            .as_sequence()
            .unwrap()
            .elements()
            .map(|e| IslTypeRefImpl::from_ion_element(isl_version, e, inline_imported_types))
            .collect::<IonSchemaResult<Vec<IslTypeRefImpl>>>()
    }

    // helper method for from_ion_element to get isl fields from given ion element
    fn isl_fields_from_ion_element(
        isl_version: IslVersion,
        value: &Element,
        inline_imported_types: &mut Vec<IslImportType>,
    ) -> IonSchemaResult<HashMap<String, IslTypeRefImpl>> {
        if value.is_null() {
            return invalid_schema_error("fields constraint was a null instead of a struct");
        }

        if value.ion_type() != IonType::Struct {
            return invalid_schema_error(format!(
                "fields constraint was a {:?} instead of a struct",
                value.ion_type()
            ));
        }

        let fields_map = value
            .as_struct()
            .unwrap()
            .iter()
            .map(|(f, v)| {
                IslTypeRefImpl::from_ion_element(isl_version, v, inline_imported_types)
                    .map(|t| (f.text().unwrap().to_owned(), t))
            })
            .collect::<IonSchemaResult<HashMap<String, IslTypeRefImpl>>>()?;

        // verify the map length with struct length to check for duplicates
        if fields_map.len() < value.as_struct().unwrap().len() {
            return invalid_schema_error("fields must be a struct with no repeated field names");
        }

        Ok(fields_map)
    }
}

/// Represents the [annotations] constraint
///
/// [annotations]: https://amazon-ion.github.io/ion-schema/docs/isl-1-0/spec#annotations
// The `required` annotation provided on the list of annotations is not represented here,
// requirement of an annotation is represented in the annotation itself by the field `is_required` of `Annotation` struct.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IslAnnotationsConstraint {
    pub is_closed: bool,
    pub is_ordered: bool,
    pub annotations: Vec<Annotation>,
}

impl IslAnnotationsConstraint {
    pub fn new(is_closed: bool, is_ordered: bool, annotations: Vec<Annotation>) -> Self {
        Self {
            is_closed,
            is_ordered,
            annotations,
        }
    }
}

impl TryFrom<&Element> for IslAnnotationsConstraint {
    type Error = IonSchemaError;

    fn try_from(value: &Element) -> IonSchemaResult<Self> {
        let annotation_modifiers: Vec<&str> = value
            .annotations()
            .iter()
            .map(|sym| sym.text().unwrap())
            .collect();

        let annotations: Vec<Annotation> = value
            .as_sequence()
            .unwrap()
            .elements()
            .map(|e| {
                Annotation::new(
                    e.as_text().unwrap().to_owned(),
                    Annotation::is_annotation_required(
                        e,
                        annotation_modifiers.contains(&"required"),
                    ),
                )
            })
            .collect();

        Ok(IslAnnotationsConstraint::new(
            annotation_modifiers.contains(&"closed"),
            annotation_modifiers.contains(&"ordered"),
            annotations,
        ))
    }
}

/// Represents the [valid_values] constraint
///
/// [valid_values]: https://amazon-ion.github.io/ion-schema/docs/isl-1-0/spec#annotations
#[derive(Debug, Clone, PartialEq)]
pub struct IslValidValuesConstraint {
    pub(crate) valid_values: Vec<ValidValue>,
}

impl IslValidValuesConstraint {
    /// Provides a way to programmatically construct valid_values constraint
    /// Returns IonSchemaError whenever annotations are provided within ValidValue::Element
    /// only `range` annotations are accepted for ValidValue::Element
    pub fn new(valid_values: Vec<ValidValue>) -> IonSchemaResult<Self> {
        let valid_values: IonSchemaResult<Vec<ValidValue>> = valid_values
            .iter()
            .map(|v| match v {
                ValidValue::Range(r) => Ok(v.to_owned()),
                ValidValue::Element(e) => e.try_into(),
            })
            .collect();
        Ok(Self {
            valid_values: valid_values?,
        })
    }

    pub fn values(&self) -> &Vec<ValidValue> {
        &self.valid_values
    }
}

impl TryFrom<&Element> for IslValidValuesConstraint {
    type Error = IonSchemaError;

    fn try_from(value: &Element) -> IonSchemaResult<Self> {
        if value.annotations().contains("range") {
            return IslValidValuesConstraint::new(vec![ValidValue::Range(
                Range::from_ion_element(value, RangeType::NumberOrTimestamp)?,
            )]);
        }
        if let Some(values) = value.as_sequence() {
            if value.ion_type() == IonType::List {
                let mut valid_values = vec![];
                let values: IonSchemaResult<Vec<()>> = values
                    .elements()
                    .map(|e| {
                        valid_values.push(e.try_into()?);
                        Ok(())
                    })
                    .collect();
                values?;
                return Ok(IslValidValuesConstraint { valid_values });
            }
        }
        invalid_schema_error(format!(
            "Expected valid_values to be a range or a list of valid values, found {}",
            value.ion_type()
        ))
    }
}

/// Represents the [regex] constraint
///
/// [regex]: https://amazon-ion.github.io/ion-schema/docs/isl-1-0/spec#regex
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IslRegexConstraint {
    case_insensitive: bool,
    multi_line: bool,
    expression: String,
}

impl IslRegexConstraint {
    pub(crate) fn new(case_insensitive: bool, multi_line: bool, expression: String) -> Self {
        Self {
            case_insensitive,
            multi_line,
            expression,
        }
    }

    pub fn expression(&self) -> &String {
        &self.expression
    }

    pub fn case_insensitive(&self) -> bool {
        self.case_insensitive
    }

    pub fn multi_line(&self) -> bool {
        self.multi_line
    }
}

/// Represents the [timestamp_offset] constraint
///
/// [timestamp_offset]: https://amazon-ion.github.io/ion-schema/docs/isl-1-0/spec#timestamp_offset
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IslTimestampOffsetConstraint {
    valid_offsets: Vec<TimestampOffset>,
}

impl IslTimestampOffsetConstraint {
    pub(crate) fn new(valid_offsets: Vec<TimestampOffset>) -> Self {
        Self { valid_offsets }
    }

    pub fn valid_offsets(&self) -> &[TimestampOffset] {
        &self.valid_offsets
    }
}