eml-nl 0.8.1

Parse, manipulate and emit EML_NL documents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
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
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
//! Document variant for the EML_NL Election Definition (`110a`) document.

use std::{collections::BTreeMap, num::NonZeroU64, str::FromStr};

use crate::{
    EMLError, EMLVersion, NS_EML, NS_KR, OASIS_EML_SCHEMA_VERSION,
    common::{
        CanonicalizationMethod, ContestIdentifier, CreationDateTime, ElectionDomain, ElectionTree,
        IssueDate, ManagingAuthority, TransactionId,
    },
    documents::ElectionIdentifierBuilder,
    error::{EMLErrorKind, EMLResultExt},
    io::{
        EMLDocument, EMLElement, EMLElementReader, EMLElementWriter, QualifiedName, collect_struct,
    },
    utils::{
        ElectionCategory, ElectionId, ElectionSubcategory, StringValue, VotingMethod, XsDate,
        XsDateOrDateTime, XsDateTime,
    },
};

pub(crate) const EML_ELECTION_DEFINITION_ID: &str = "110a";

/// Representing a `110a` document, containing an election definition.
#[derive(Debug, Clone)]
pub struct ElectionDefinition {
    /// EML_NL version of the document
    pub version: EMLVersion,

    /// Transaction id of the document.
    pub transaction_id: TransactionId,

    /// Managing authority of the election, if present.
    pub managing_authority: Option<ManagingAuthority>,

    /// Issue date of the election definition, if present.
    pub issue_date: Option<IssueDate>,

    /// Time this document was created.
    pub creation_date_time: CreationDateTime,

    /// Canonicalization method used in this document, if present.
    pub canonicalization_method: Option<CanonicalizationMethod>,

    /// The election event defined in this document.
    pub election_event: ElectionDefinitionElectionEvent,
}

impl ElectionDefinition {
    /// Create a new builder for [`ElectionDefinition`].
    pub fn builder() -> ElectionDefinitionBuilder {
        ElectionDefinitionBuilder::new()
    }
}

impl EMLDocument for ElectionDefinition {
    fn document_version(&self) -> EMLVersion {
        self.version
    }

    fn document_eml_id(&self) -> &'static str {
        EML_ELECTION_DEFINITION_ID
    }

    fn document_friendly_name(&self) -> &'static str {
        "Election Definition"
    }

    fn document_namespaces(&self) -> Option<BTreeMap<&'static str, &'static str>> {
        None
    }
}

impl FromStr for ElectionDefinition {
    type Err = EMLError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        use crate::io::EMLRead as _;
        Self::parse_eml(s, crate::io::EMLParsingMode::Strict).ok()
    }
}

impl TryFrom<&str> for ElectionDefinition {
    type Error = EMLError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        use crate::io::EMLRead as _;
        Self::parse_eml(value, crate::io::EMLParsingMode::Strict).ok()
    }
}

impl TryFrom<ElectionDefinition> for String {
    type Error = EMLError;

    fn try_from(value: ElectionDefinition) -> Result<Self, Self::Error> {
        use crate::io::EMLWrite as _;
        value.write_eml_root_str(true, true)
    }
}

/// Builder for [`ElectionDefinition`].
#[derive(Debug, Clone)]
pub struct ElectionDefinitionBuilder {
    version: Option<EMLVersion>,
    transaction_id: Option<TransactionId>,
    managing_authority: Option<ManagingAuthority>,
    issue_date: Option<IssueDate>,
    creation_date_time: Option<CreationDateTime>,
    canonicalization_method: Option<CanonicalizationMethod>,
    election_event: Option<ElectionDefinitionElectionEvent>,
    election_identifier: Option<ElectionDefinitionElectionIdentifier>,
    number_of_seats: Option<StringValue<u64>>,
    preference_threshold: Option<StringValue<u64>>,
    election_tree: Option<ElectionTree>,
    registered_parties: Vec<ElectionDefinitionRegisteredParty>,
    contest_identifier: Option<ContestIdentifier>,
    voting_method: Option<StringValue<VotingMethod>>,
    max_votes: Option<StringValue<NonZeroU64>>,
}

impl ElectionDefinitionBuilder {
    /// Create a new builder for [`ElectionDefinition`].
    pub fn new() -> Self {
        Self {
            version: None,
            transaction_id: None,
            managing_authority: None,
            issue_date: None,
            creation_date_time: None,
            canonicalization_method: None,
            election_event: None,
            election_identifier: None,
            number_of_seats: None,
            preference_threshold: None,
            election_tree: None,
            registered_parties: vec![],
            contest_identifier: None,
            voting_method: None,
            max_votes: None,
        }
    }

    /// Set the version for the document.
    ///
    /// If not set, the default version is used.
    pub fn version(mut self, version: impl Into<EMLVersion>) -> Self {
        self.version = Some(version.into());
        self
    }

    /// Set the transaction id for the document.
    pub fn transaction_id(mut self, transaction_id: impl Into<TransactionId>) -> Self {
        self.transaction_id = Some(transaction_id.into());
        self
    }

    /// Set the managing authority for the document.
    pub fn managing_authority(mut self, managing_authority: impl Into<ManagingAuthority>) -> Self {
        self.managing_authority = Some(managing_authority.into());
        self
    }

    /// Set the issue date for the document.
    pub fn issue_date(mut self, issue_date: impl Into<XsDateOrDateTime>) -> Self {
        self.issue_date = Some(IssueDate::new(issue_date.into()));
        self
    }

    /// Set the creation date and time for the document.
    pub fn creation_date_time(mut self, creation_date_time: impl Into<XsDateTime>) -> Self {
        self.creation_date_time = Some(CreationDateTime::new(creation_date_time.into()));
        self
    }

    /// Set the canonicalization method for the document.
    pub fn canonicalization_method(
        mut self,
        canonicalization_method: impl Into<CanonicalizationMethod>,
    ) -> Self {
        self.canonicalization_method = Some(canonicalization_method.into());
        self
    }

    /// Set the election event containing the election definition
    pub fn election_event(
        mut self,
        election_event: impl Into<ElectionDefinitionElectionEvent>,
    ) -> Self {
        self.election_event = Some(election_event.into());
        self
    }

    /// Set the election identifier for the election event.
    pub fn election_identifier(
        mut self,
        election_identifier: impl Into<ElectionDefinitionElectionIdentifier>,
    ) -> Self {
        self.election_identifier = Some(election_identifier.into());
        self
    }

    /// Set the number of seats for the election.
    pub fn number_of_seats(mut self, number_of_seats: impl Into<u64>) -> Self {
        self.number_of_seats = Some(StringValue::from_value(number_of_seats.into()));
        self
    }

    /// Set the preference threshold for the election.
    ///
    /// This is optional: if not set, [`Self::build`] will fill in the correct value as
    /// required by Dutch election law for the election's subcategory.
    pub fn preference_threshold(mut self, preference_threshold: impl Into<u64>) -> Self {
        self.preference_threshold = Some(StringValue::from_value(preference_threshold.into()));
        self
    }

    /// Set the election tree for the election.
    pub fn election_tree(mut self, election_tree: impl Into<ElectionTree>) -> Self {
        self.election_tree = Some(election_tree.into());
        self
    }

    /// Set the registered parties for the election.
    pub fn registered_parties(
        mut self,
        registered_parties: impl Into<Vec<ElectionDefinitionRegisteredParty>>,
    ) -> Self {
        self.registered_parties = registered_parties.into();
        self
    }

    /// Add a registered party to the election.
    pub fn push_registered_party(
        mut self,
        party: impl Into<ElectionDefinitionRegisteredParty>,
    ) -> Self {
        self.registered_parties.push(party.into());
        self
    }

    /// Set the contest identifier for the election.
    pub fn contest_identifier(mut self, contest_identifier: impl Into<ContestIdentifier>) -> Self {
        self.contest_identifier = Some(contest_identifier.into());
        self
    }

    /// Set the voting method for the election.
    pub fn voting_method(mut self, voting_method: impl Into<VotingMethod>) -> Self {
        self.voting_method = Some(StringValue::from_value(voting_method.into()));
        self
    }

    /// Set the maximum number of votes for the election (number of eligible voters).
    /// EML specifies the default value as 1, so providing the value of 1 will result in an empty xml tag.
    pub fn max_votes(mut self, max_votes: impl Into<NonZeroU64>) -> Self {
        self.max_votes = Some(StringValue::from_value(max_votes.into()));
        self
    }

    /// Build the [`ElectionDefinition`] from the provided values, returning an error if any required fields are missing.
    pub fn build(self) -> Result<ElectionDefinition, EMLError> {
        Ok(ElectionDefinition {
            version: self.version.unwrap_or_default(),
            transaction_id: self
                .transaction_id
                .ok_or(EMLErrorKind::MissingBuildProperty("transaction_id").without_span())?,
            managing_authority: self.managing_authority,
            issue_date: self.issue_date,
            creation_date_time: self
                .creation_date_time
                .ok_or(EMLErrorKind::MissingBuildProperty("creation_date_time").without_span())?,
            canonicalization_method: self.canonicalization_method,
            election_event: self.election_event.map_or_else(
                || {
                    let election_identifier = self.election_identifier.ok_or(
                        EMLErrorKind::MissingBuildProperty("election_identifier").without_span(),
                    )?;
                    let subcategory = election_identifier.subcategory.copied_value().ok();

                    let election_details = ElectionDefinitionElection {
                        identifier: election_identifier,
                        contest: ElectionDefinitionContest::new(
                            self.contest_identifier.ok_or(
                                EMLErrorKind::MissingBuildProperty("contest_identifier")
                                    .without_span(),
                            )?,
                            self.voting_method.ok_or(
                                EMLErrorKind::MissingBuildProperty("voting_method").without_span(),
                            )?,
                            self.max_votes.ok_or(
                                EMLErrorKind::MissingBuildProperty("max_votes").without_span(),
                            )?,
                        ),
                        number_of_seats: self.number_of_seats.ok_or(
                            EMLErrorKind::MissingBuildProperty("number_of_seats").without_span(),
                        )?,
                        preference_threshold: self.preference_threshold.unwrap_or_else(|| {
                            StringValue::from_value(expected_preference_threshold(subcategory))
                        }),
                        election_tree: self.election_tree.ok_or(
                            EMLErrorKind::MissingBuildProperty("election_tree").without_span(),
                        )?,
                        registered_parties: self.registered_parties,
                    };

                    validate_election_details(&election_details)?;

                    Ok::<_, EMLError>(election_details.into())
                },
                Ok,
            )?,
        })
    }
}

fn expected_preference_threshold(subcategory: Option<ElectionSubcategory>) -> u64 {
    match subcategory {
        Some(ElectionSubcategory::GR1) => 50, // Kieswet P 15, Lid 2
        Some(ElectionSubcategory::KCCN | ElectionSubcategory::KCNI) => 50, // Kieswet Ya 29a
        Some(ElectionSubcategory::EK) => 100, // Kieswet U 15, Lid 1
        Some(ElectionSubcategory::EP) => 10,  // Kieswet Y 23a
        _ => 25,                              // Kieswet P 15, Lid 1 (default value)
    }
}

fn validate_election_details(election: &ElectionDefinitionElection) -> Result<(), EMLError> {
    let subcategory = election.identifier.subcategory.copied_value().ok();
    let preference_threshold = election.preference_threshold.copied_value().ok();
    let number_of_seats = election.number_of_seats.copied_value().ok();
    let voting_method = election.contest.voting_method.copied_value().ok();
    let mut errors = vec![];
    if let Some(voting_method) = voting_method
        && voting_method != VotingMethod::SPV
    {
        // All election supported should use the SPV voting method
        errors.push(EMLErrorKind::UnsupportedVotingMethod.without_span());
    }

    if let Some(pt) = preference_threshold
        && pt != expected_preference_threshold(subcategory)
    {
        // All elections should use the expected preference threshold for their subcategory
        errors.push(EMLErrorKind::InvalidPreferenceThreshold.without_span());
    }

    match (subcategory, number_of_seats) {
        (Some(ElectionSubcategory::GR1), Some(seat_count)) if seat_count >= 19 => {
            // For GR1 elections: number of seats should be less than 19

            errors.push(EMLErrorKind::InvalidNumberOfSeats.without_span());
        }
        (Some(ElectionSubcategory::GR2), Some(seats)) if seats < 19 => {
            // For GR2 elections: number of seats should be 19 or more

            errors.push(EMLErrorKind::InvalidNumberOfSeats.without_span());
        }
        (Some(ElectionSubcategory::AB1), Some(seats)) if seats >= 19 => {
            // For AB1 elections: number of seats should be less than 19

            errors.push(EMLErrorKind::InvalidNumberOfSeats.without_span());
        }
        (Some(ElectionSubcategory::AB2), Some(seats)) if seats < 19 => {
            // For AB2 elections: number of seats should be 19 or more

            errors.push(EMLErrorKind::InvalidNumberOfSeats.without_span());
        }
        _ => {
            // Anything else is valid
        }
    }

    if !errors.is_empty() {
        return Err(EMLError::from_vec(errors));
    }

    Ok(())
}

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

impl EMLElement for ElectionDefinition {
    const EML_NAME: QualifiedName<'_, '_> = QualifiedName::from_static("EML", Some(NS_EML));

    fn read_eml(elem: &mut EMLElementReader<'_, '_>) -> Result<Self, EMLError> {
        let document_id = elem.attribute_value_req(("Id", None))?;
        if document_id != EML_ELECTION_DEFINITION_ID {
            return Err(EMLErrorKind::InvalidDocumentType(
                EML_ELECTION_DEFINITION_ID,
                document_id.to_string(),
            ))
            .with_span(elem.span());
        }

        Ok(collect_struct!(elem, ElectionDefinition {
            version as Default(EMLVersion::V1_2_2): EMLVersion::EML_NAME => |elem| elem.read_element::<EMLVersion>()?,
            transaction_id: TransactionId::EML_NAME => |elem| elem.read_element::<TransactionId>()?,
            managing_authority as Option: ManagingAuthority::EML_NAME => |elem| elem.read_element::<ManagingAuthority>()?,
            issue_date as Option: IssueDate::EML_NAME => |elem| elem.read_element::<IssueDate>()?,
            creation_date_time: CreationDateTime::EML_NAME => |elem| elem.read_element::<CreationDateTime>()?,
            canonicalization_method as Option: CanonicalizationMethod::EML_NAME => |elem| elem.read_element::<CanonicalizationMethod>()?,
            election_event: ElectionDefinitionElectionEvent::EML_NAME => |elem| elem.read_element::<ElectionDefinitionElectionEvent>()?,
        }))
    }

    fn write_eml(&self, writer: EMLElementWriter) -> Result<(), EMLError> {
        writer
            .attr(("Id", None), EML_ELECTION_DEFINITION_ID)?
            .attr(("SchemaVersion", None), OASIS_EML_SCHEMA_VERSION)?
            .child_elem(TransactionId::EML_NAME, &self.transaction_id)?
            .child_elem_option(
                ManagingAuthority::EML_NAME,
                self.managing_authority.as_ref(),
            )?
            .child_elem_option(IssueDate::EML_NAME, self.issue_date.as_ref())?
            .child_option(
                EMLVersion::EML_NAME,
                self.version.to_str(),
                |elem, version| elem.attr("Version", version)?.empty(),
            )?
            .child_elem(CreationDateTime::EML_NAME, &self.creation_date_time)?
            // Note: we don't output the CanonicalizationMethod because we aren't canonicalizing our output
            // .child_elem_option(
            //     CanonicalizationMethod::EML_NAME,
            //     self.canonicalization_method.as_ref(),
            // )?
            .child_elem(
                ElectionDefinitionElectionEvent::EML_NAME,
                &self.election_event,
            )?
            .finish()
    }
}

/// Election event defined in the election definition document.
#[derive(Debug, Clone)]
pub struct ElectionDefinitionElectionEvent {
    /// Election details.
    pub election: ElectionDefinitionElection,
}

impl ElectionDefinitionElectionEvent {
    /// Create a new election event with the provided election details.
    pub fn new(election: impl Into<ElectionDefinitionElection>) -> Self {
        Self {
            election: election.into(),
        }
    }
}

impl From<ElectionDefinitionElection> for ElectionDefinitionElectionEvent {
    fn from(election: ElectionDefinitionElection) -> Self {
        Self::new(election)
    }
}

impl EMLElement for ElectionDefinitionElectionEvent {
    const EML_NAME: QualifiedName<'_, '_> =
        QualifiedName::from_static("ElectionEvent", Some(NS_EML));

    fn read_eml(elem: &mut EMLElementReader<'_, '_>) -> Result<Self, EMLError> {
        Ok(collect_struct!(elem, ElectionDefinitionElectionEvent {
            id as None: ("EventIdentifier", NS_EML) => |elem| elem.skip().map(|_| ())?,
            election: ElectionDefinitionElection::EML_NAME => |elem| elem.read_element::<ElectionDefinitionElection>()?,
        }))
    }

    fn write_eml(&self, writer: EMLElementWriter) -> Result<(), EMLError> {
        writer
            .child(("EventIdentifier", NS_EML), |w| w.empty())?
            .child_elem(ElectionDefinitionElection::EML_NAME, &self.election)?
            .finish()
    }
}

/// Name for the number of seats element
const EML_NAME_NUMBER_OF_SEATS: QualifiedName<'_, '_> =
    QualifiedName::from_static("NumberOfSeats", Some(NS_KR));

/// Name for the preference threshold element
const EML_NAME_PREFERENCE_THRESHOLD: QualifiedName<'_, '_> =
    QualifiedName::from_static("PreferenceThreshold", Some(NS_KR));

/// Election details for an election definition.
#[derive(Debug, Clone)]
pub struct ElectionDefinitionElection {
    /// Identifier
    pub identifier: ElectionDefinitionElectionIdentifier,

    /// Election voting method details
    pub contest: ElectionDefinitionContest,

    /// Number of seats in the election
    pub number_of_seats: StringValue<u64>,

    /// The preference threshold percentage
    pub preference_threshold: StringValue<u64>,

    /// Election tree for this election
    pub election_tree: ElectionTree,

    /// A list of registered parties.
    pub registered_parties: Vec<ElectionDefinitionRegisteredParty>,
}

impl EMLElement for ElectionDefinitionElection {
    const EML_NAME: QualifiedName<'_, '_> = QualifiedName::from_static("Election", Some(NS_EML));

    fn read_eml(elem: &mut EMLElementReader<'_, '_>) -> Result<Self, EMLError> {
        let data = collect_struct!(elem, ElectionDefinitionElection {
            identifier: ElectionDefinitionElectionIdentifier::EML_NAME => |elem| elem.read_element::<ElectionDefinitionElectionIdentifier>()?,
            contest: ElectionDefinitionContest::EML_NAME => |elem| elem.read_element::<ElectionDefinitionContest>()?,
            number_of_seats: EML_NAME_NUMBER_OF_SEATS => |elem| elem.string_value()?,
            preference_threshold: EML_NAME_PREFERENCE_THRESHOLD => |elem| elem.string_value()?,
            election_tree: ElectionTree::EML_NAME => |elem| elem.read_element::<ElectionTree>()?,
            registered_parties: ("RegisteredParties", NS_KR) => |elem| ElectionDefinitionRegisteredParty::read_list(elem)?,
        });

        if let Err(errors) = validate_election_details(&data) {
            if elem.parsing_mode().is_strict() {
                return Err(errors);
            } else {
                elem.push_err(errors);
            }
        }

        Ok(data)
    }

    fn write_eml(&self, writer: EMLElementWriter) -> Result<(), EMLError> {
        writer
            .child_elem(
                ElectionDefinitionElectionIdentifier::EML_NAME,
                &self.identifier,
            )?
            .child_elem(ElectionDefinitionContest::EML_NAME, &self.contest)?
            .child(EML_NAME_NUMBER_OF_SEATS, |elem| {
                elem.text(self.number_of_seats.raw().as_ref())?.finish()
            })?
            .child(EML_NAME_PREFERENCE_THRESHOLD, |elem| {
                elem.text(self.preference_threshold.raw().as_ref())?
                    .finish()
            })?
            .child_elem(ElectionTree::EML_NAME, &self.election_tree)?
            .child(("RegisteredParties", NS_KR), |elem| {
                ElectionDefinitionRegisteredParty::write_list(&self.registered_parties, elem)
            })?
            .finish()
    }
}

/// Identifier for the election.
#[derive(Debug, Clone)]
pub struct ElectionDefinitionElectionIdentifier {
    /// Id of the election
    pub id: StringValue<ElectionId>,

    /// Name of the election
    pub name: Box<str>,

    /// Category of the election
    pub category: StringValue<ElectionCategory>,

    /// Subcategory of the election
    pub subcategory: StringValue<ElectionSubcategory>,

    /// The (top level) region where the election takes place.
    pub domain: Option<ElectionDomain>,

    /// Date of the election
    pub election_date: StringValue<XsDate>,

    /// Nomination date for the election
    pub nomination_date: StringValue<XsDate>,
}

impl ElectionDefinitionElectionIdentifier {
    /// Create a builder for the [`ElectionDefinitionElectionIdentifier`].
    /// Note: this is a generic builder, use the [`ElectionIdentifierBuilder::build_for_definition`] method for an election definition specific builder that will fill in the correct category and subcategory.
    pub fn builder() -> ElectionIdentifierBuilder {
        ElectionIdentifierBuilder::new()
    }
}

impl EMLElement for ElectionDefinitionElectionIdentifier {
    const EML_NAME: QualifiedName<'_, '_> =
        QualifiedName::from_static("ElectionIdentifier", Some(NS_EML));

    fn read_eml(elem: &mut EMLElementReader<'_, '_>) -> Result<Self, EMLError> {
        let data = collect_struct!(
            elem,
            ElectionDefinitionElectionIdentifier {
                id: elem.string_value_attr("Id", None)?,
                name: ("ElectionName", NS_EML) => |elem| elem.text_without_children()?,
                category: ("ElectionCategory", NS_EML) => |elem| ElectionCategory::read_and_validate(elem)?,
                subcategory: ("ElectionSubcategory", NS_KR) => |elem| elem.string_value()?,
                domain as Option: ElectionDomain::EML_NAME => |elem| elem.read_element::<ElectionDomain>()?,
                election_date: ("ElectionDate", NS_KR) => |elem| elem.string_value()?,
                nomination_date: ("NominationDate", NS_KR) => |elem| elem.string_value()?,
            }
        );

        elem.report_validation(
            data.election_date.validate_is_after(
                &data.nomination_date,
                EMLErrorKind::NominationDateNotBeforeElectionDate,
            ),
            elem.full_span(),
        )?;

        elem.report_validation(
            data.category.validate_subcategory(Some(&data.subcategory)),
            elem.full_span(),
        )?;

        Ok(data)
    }

    fn write_eml(&self, writer: EMLElementWriter) -> Result<(), EMLError> {
        self.category.validate_version(writer.document_version())?;

        writer
            .attr("Id", self.id.raw().as_ref())?
            .child(("ElectionName", NS_EML), |elem| {
                elem.text(self.name.as_ref())?.finish()
            })?
            .child(("ElectionCategory", NS_EML), |elem| {
                elem.text(self.category.raw().as_ref())?.finish()
            })?
            .child(("ElectionSubcategory", NS_KR), |elem| {
                elem.text(self.subcategory.raw().as_ref())?.finish()
            })?
            .child_elem_option(ElectionDomain::EML_NAME, self.domain.as_ref())?
            .child(("ElectionDate", NS_KR), |elem| {
                elem.text(self.election_date.raw().as_ref())?.finish()
            })?
            .child(("NominationDate", NS_KR), |elem| {
                elem.text(self.nomination_date.raw().as_ref())?.finish()
            })?
            .finish()
    }
}

/// Contains details about the voting methods for the election.
#[derive(Debug, Clone)]
pub struct ElectionDefinitionContest {
    /// Identifier for the contest.
    pub identifier: ContestIdentifier,

    /// Voting method used in the contest.
    pub voting_method: StringValue<VotingMethod>,

    /// Maximum number of votes allowed.
    /// EML specifies the default value as 1, so an empty tag will be parsed as 1 and vice versa.
    pub max_votes: StringValue<NonZeroU64>,
}

impl ElectionDefinitionContest {
    /// Create a new contest with the provided details.
    pub fn new(
        identifier: impl Into<ContestIdentifier>,
        voting_method: impl Into<StringValue<VotingMethod>>,
        max_votes: impl Into<StringValue<NonZeroU64>>,
    ) -> Self {
        Self {
            identifier: identifier.into(),
            voting_method: voting_method.into(),
            max_votes: max_votes.into(),
        }
    }
}

impl EMLElement for ElectionDefinitionContest {
    const EML_NAME: QualifiedName<'_, '_> = QualifiedName::from_static("Contest", Some(NS_EML));

    fn read_eml(elem: &mut EMLElementReader<'_, '_>) -> Result<Self, EMLError> {
        Ok(collect_struct!(elem, ElectionDefinitionContest {
            identifier: ContestIdentifier::EML_NAME => |elem| elem.read_element::<ContestIdentifier>()?,
            voting_method: ("VotingMethod", NS_EML) => |elem| elem.string_value()?,
            max_votes: ("MaxVotes", NS_EML) => |elem| {
                // Default value of MaxVotes in EML is 1
                let text = elem.text_without_children_opt()?.unwrap_or_else(|| "1".into());
                elem.string_value_from_text(text, None, elem.full_span())?
            },
        }))
    }

    fn write_eml(&self, writer: EMLElementWriter) -> Result<(), EMLError> {
        writer
            .child_elem(ContestIdentifier::EML_NAME, &self.identifier)?
            .child(("VotingMethod", NS_EML), |elem| {
                elem.text(self.voting_method.raw().as_ref())?.finish()
            })?
            .child(("MaxVotes", NS_EML), |elem| {
                let raw_text = self.max_votes.raw();
                // Default value of MaxVotes in EML is 1
                if raw_text == "1" {
                    elem.empty()
                } else {
                    elem.text(raw_text.as_ref())?.finish()
                }
            })?
            .finish()
    }
}

/// A registered party in the election definition.
///
/// In election definitions this is just a party name, for full party details and
/// candidates see the [`CandidateLists`](crate::documents::candidate_lists::CandidateLists)
/// document.
#[derive(Debug, Clone)]
pub struct ElectionDefinitionRegisteredParty {
    /// Name of the registered party (as registered at the CSB)
    pub registered_appellation: Box<str>,
}

impl ElectionDefinitionRegisteredParty {
    /// Create a new registered party with the provided name.
    pub fn new(registered_appellation: impl Into<Box<str>>) -> Self {
        Self {
            registered_appellation: registered_appellation.into(),
        }
    }
}

impl From<String> for ElectionDefinitionRegisteredParty {
    fn from(value: String) -> Self {
        Self::new(value)
    }
}

impl From<Box<str>> for ElectionDefinitionRegisteredParty {
    fn from(value: Box<str>) -> Self {
        Self::new(value)
    }
}

impl From<&str> for ElectionDefinitionRegisteredParty {
    fn from(value: &str) -> Self {
        Self::new(value.to_string())
    }
}

impl ElectionDefinitionRegisteredParty {
    pub(crate) fn read_list(
        elem: &mut EMLElementReader<'_, '_>,
    ) -> Result<Vec<ElectionDefinitionRegisteredParty>, EMLError> {
        let mut parties = Vec::new();
        let elem_name = elem.name()?.as_owned();
        while let Some(mut child) = elem.next_child()? {
            if child.has_name(ElectionDefinitionRegisteredParty::EML_NAME)? {
                let party = ElectionDefinitionRegisteredParty::read_eml(&mut child)?;
                parties.push(party);
            } else {
                return Err(EMLErrorKind::UnexpectedElement(
                    child.name()?.as_owned(),
                    elem_name,
                ))
                .with_span(child.span());
            }
        }
        Ok(parties)
    }

    pub(crate) fn write_list(
        parties: &[ElectionDefinitionRegisteredParty],
        writer: EMLElementWriter,
    ) -> Result<(), EMLError> {
        if parties.is_empty() {
            return writer.empty();
        }

        let mut content = writer.content()?;
        for party in parties {
            content = content.child_elem(ElectionDefinitionRegisteredParty::EML_NAME, party)?;
        }
        content.finish()
    }
}

impl EMLElement for ElectionDefinitionRegisteredParty {
    const EML_NAME: QualifiedName<'_, '_> =
        QualifiedName::from_static("RegisteredParty", Some(NS_KR));

    fn read_eml(elem: &mut EMLElementReader<'_, '_>) -> Result<Self, EMLError> {
        Ok(collect_struct!(elem, ElectionDefinitionRegisteredParty {
            registered_appellation: ("RegisteredAppellation", NS_KR) => |elem| elem.text_without_children()?,
        }))
    }

    fn write_eml(&self, writer: EMLElementWriter) -> Result<(), EMLError> {
        writer
            .child(("RegisteredAppellation", NS_KR), |elem| {
                elem.text(self.registered_appellation.as_ref())?.finish()
            })?
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use chrono::TimeZone as _;

    use crate::{
        common::Region,
        io::{EMLParsingMode, EMLRead as _, EMLWrite},
        utils::{AuthorityId, RegionCategory},
    };

    use super::*;

    #[test]
    fn test_election_definition_construction() {
        let election_definition = ElectionDefinition::builder()
            .version(EMLVersion::V1_2_2)
            .transaction_id(TransactionId::new(1))
            .managing_authority(ManagingAuthority::new(AuthorityId::new("1234").unwrap()))
            .issue_date(XsDate::from_date(2024, 6, 10).unwrap())
            .creation_date_time(
                chrono::Utc
                    .with_ymd_and_hms(2014, 11, 28, 12, 0, 9)
                    .unwrap(),
            )
            .election_identifier(
                ElectionDefinitionElectionIdentifier::builder()
                    .id(ElectionId::new("GR2026_Test").unwrap())
                    .name("Test election")
                    .category(ElectionCategory::GR)
                    .subcategory(ElectionSubcategory::GR1)
                    .election_date(XsDate::from_date(2024, 11, 5).unwrap())
                    .nomination_date(XsDate::from_date(2024, 10, 1).unwrap())
                    .build_for_definition()
                    .unwrap(),
            )
            .contest_identifier(ContestIdentifier::geen())
            .voting_method(VotingMethod::SPV)
            .max_votes(NonZeroU64::new(100).unwrap())
            .number_of_seats(10u32)
            .election_tree(ElectionTree::new(vec![Region::new(
                "Region 1",
                RegionCategory::Municipality,
            )]))
            .push_registered_party("Party a")
            .push_registered_party("Party one")
            .build()
            .unwrap();

        let xml = election_definition.write_eml_root_str(true, true).unwrap();
        assert_eq!(
            xml,
            include_str!(
                "../../test-files/election_definition/eml110a_election_definition_construction_output.eml.xml"
            )
        );

        // check if it still is the same after a second parse and write
        let parsed = ElectionDefinition::parse_eml(&xml, EMLParsingMode::Strict).unwrap();
        let xml2 = parsed.write_eml_root_str(true, true).unwrap();
        assert_eq!(xml, xml2);
    }

    #[test]
    fn test_read_election_definition_with_max_votes_empty() {
        let xml = include_str!("../../test-files/election_definition/eml110a_test.eml.xml");

        let parsed = ElectionDefinition::parse_eml(xml, EMLParsingMode::Strict).unwrap();
        // empty MaxVotes should be parsed to 1, because 1 is the default value according to the EML standard
        assert_eq!(
            parsed.election_event.election.contest.max_votes,
            StringValue::Parsed(NonZeroU64::new(1).unwrap())
        );
    }

    #[test]
    fn test_write_election_definition_with_max_votes_empty() {
        let election_definition = ElectionDefinition::builder()
            .transaction_id(TransactionId::new(1))
            .managing_authority(ManagingAuthority::new(AuthorityId::new("1234").unwrap()))
            .issue_date(XsDate::from_date(2024, 6, 10).unwrap())
            .creation_date_time(
                chrono::Utc
                    .with_ymd_and_hms(2014, 11, 28, 12, 0, 9)
                    .unwrap(),
            )
            .election_identifier(
                ElectionDefinitionElectionIdentifier::builder()
                    .id(ElectionId::new("GR2026_Test").unwrap())
                    .name("Test election")
                    .category(ElectionCategory::GR)
                    .subcategory(ElectionSubcategory::GR1)
                    .election_date(XsDate::from_date(2024, 11, 5).unwrap())
                    .nomination_date(XsDate::from_date(2024, 10, 1).unwrap())
                    .build_for_definition()
                    .unwrap(),
            )
            .contest_identifier(ContestIdentifier::geen())
            .voting_method(VotingMethod::SPV)
            .max_votes(NonZeroU64::new(1).unwrap())
            .number_of_seats(10u32)
            .preference_threshold(50u32)
            .election_tree(ElectionTree::new(vec![Region::new(
                "Region 1",
                RegionCategory::Municipality,
            )]))
            .push_registered_party("Party a")
            .push_registered_party("Party one")
            .build()
            .unwrap();

        let xml = election_definition.write_eml_root_str(true, true).unwrap();
        // max_votes of 1 should result in an empty MaxVotes tag, because 1 is the default value according to the EML standard
        assert!(xml.contains("<MaxVotes/>"))
    }

    #[test]
    fn test_invalid_election_date_format() {
        let xml = include_str!(
            "../../test-files/election_definition/eml110a_invalid_election_date_format.eml.xml"
        );

        let result = ElectionDefinition::parse_eml(xml, EMLParsingMode::Strict).ok_with_errors();
        assert!(result.is_err());
    }

    #[test]
    fn test_invalid_election_date_nomination_format() {
        let xml = include_str!(
            "../../test-files/election_definition/eml110a_invalid_election_date_nomination_format.eml.xml"
        );

        let result = ElectionDefinition::parse_eml(xml, EMLParsingMode::Strict).ok_with_errors();
        assert!(result.is_err());
    }

    #[test]
    fn test_invalid_election_mismatch_preference_threshold() {
        let xml = include_str!(
            "../../test-files/election_definition/eml110a_invalid_election_mismatch_preference_threshold.eml.xml"
        );

        let result = ElectionDefinition::parse_eml(xml, EMLParsingMode::Strict).ok_with_errors();
        assert!(result.is_err());
    }

    #[test]
    fn test_invalid_election_mismatch_preference_threshold_small_election() {
        let xml = include_str!(
            "../../test-files/election_definition/eml110a_invalid_election_mismatch_preference_threshold_small_election.eml.xml"
        );

        let result = ElectionDefinition::parse_eml(xml, EMLParsingMode::Strict).ok_with_errors();
        assert!(result.is_err());
    }

    /// Helper to build an [`ElectionDefinition`] with the given category, subcategory and
    /// preference threshold, for testing [`validate_election_details`].
    fn build_with_preference_threshold(
        category: ElectionCategory,
        subcategory: ElectionSubcategory,
        preference_threshold: u32,
    ) -> Result<ElectionDefinition, EMLError> {
        ElectionDefinition::builder()
            .transaction_id(TransactionId::new(1))
            .creation_date_time(
                chrono::Utc
                    .with_ymd_and_hms(2014, 11, 28, 12, 0, 9)
                    .unwrap(),
            )
            .election_identifier(
                ElectionDefinitionElectionIdentifier::builder()
                    .id(ElectionId::new("EK2023_Test").unwrap())
                    .name("Test election")
                    .category(category)
                    .subcategory(subcategory)
                    .election_date(XsDate::from_date(2024, 11, 5).unwrap())
                    .nomination_date(XsDate::from_date(2024, 10, 1).unwrap())
                    .build_for_definition()
                    .unwrap(),
            )
            .contest_identifier(ContestIdentifier::geen())
            .voting_method(VotingMethod::SPV)
            .max_votes(NonZeroU64::new(100).unwrap())
            .number_of_seats(75u32)
            .preference_threshold(preference_threshold)
            .election_tree(ElectionTree::new(vec![Region::new(
                "Region 1",
                RegionCategory::Municipality,
            )]))
            .build()
    }

    #[test]
    fn test_preference_threshold_ek() {
        // Kieswet U 15, Lid 1: for EK elections, the preference threshold should be 100%
        assert!(
            build_with_preference_threshold(ElectionCategory::EK, ElectionSubcategory::EK, 100)
                .is_ok()
        );
        assert!(
            build_with_preference_threshold(ElectionCategory::EK, ElectionSubcategory::EK, 25)
                .is_err()
        );
    }

    #[test]
    fn test_preference_threshold_ep() {
        // Kieswet Y 23a: for EP elections, the preference threshold should be 10$
        assert!(
            build_with_preference_threshold(ElectionCategory::EP, ElectionSubcategory::EP, 10)
                .is_ok()
        );
        assert!(
            build_with_preference_threshold(ElectionCategory::EP, ElectionSubcategory::EP, 25)
                .is_err()
        );
    }

    #[test]
    fn test_preference_threshold_kiescollege() {
        // Kieswet Ya 29a: for kiescollege elections, the preference threshold should be 50%
        assert!(
            build_with_preference_threshold(ElectionCategory::KC, ElectionSubcategory::KCCN, 50)
                .is_ok()
        );
        assert!(
            build_with_preference_threshold(ElectionCategory::KC, ElectionSubcategory::KCCN, 25)
                .is_err()
        );
        assert!(
            build_with_preference_threshold(ElectionCategory::KC, ElectionSubcategory::KCNI, 50)
                .is_ok()
        );
        assert!(
            build_with_preference_threshold(ElectionCategory::KC, ElectionSubcategory::KCNI, 25)
                .is_err()
        );
    }

    #[test]
    fn test_write_rejects_kc_category_before_v1_3() {
        let build = |version: EMLVersion| {
            ElectionDefinition::builder()
                .version(version)
                .transaction_id(TransactionId::new(1))
                .creation_date_time(
                    chrono::Utc
                        .with_ymd_and_hms(2014, 11, 28, 12, 0, 9)
                        .unwrap(),
                )
                .election_identifier(
                    ElectionDefinitionElectionIdentifier::builder()
                        .id(ElectionId::new("KC2023_Test").unwrap())
                        .name("Test election")
                        .category(ElectionCategory::KC)
                        .subcategory(ElectionSubcategory::KCCN)
                        .election_date(XsDate::from_date(2024, 11, 5).unwrap())
                        .nomination_date(XsDate::from_date(2024, 10, 1).unwrap())
                        .build_for_definition()
                        .unwrap(),
                )
                .contest_identifier(ContestIdentifier::geen())
                .voting_method(VotingMethod::SPV)
                .max_votes(NonZeroU64::new(100).unwrap())
                .number_of_seats(75u32)
                .preference_threshold(50u32)
                .election_tree(ElectionTree::new(vec![Region::new(
                    "Region 1",
                    RegionCategory::Municipality,
                )]))
                .build()
                .unwrap()
        };

        assert!(
            build(EMLVersion::V1_2_2)
                .write_eml_root_str(true, true)
                .is_err()
        );
        assert!(
            build(EMLVersion::V1_3)
                .write_eml_root_str(true, true)
                .is_ok()
        );
    }

    #[test]
    fn test_election_missing_election_domain() {
        let xml = include_str!(
            "../../test-files/election_definition/eml110a_election_missing_election_domain.eml.xml"
        );

        let result = ElectionDefinition::parse_eml(xml, EMLParsingMode::Strict).ok_with_errors();
        assert!(result.is_ok());
    }

    #[test]
    fn test_invalid_election_missing_election_tree() {
        let xml = include_str!(
            "../../test-files/election_definition/eml110a_invalid_election_missing_election_tree.eml.xml"
        );

        let result = ElectionDefinition::parse_eml(xml, EMLParsingMode::Strict).ok_with_errors();
        assert!(result.is_err());
    }

    #[test]
    fn test_invalid_election_missing_nomination_date() {
        let xml = include_str!(
            "../../test-files/election_definition/eml110a_invalid_election_missing_nomination_date.eml.xml"
        );

        let result = ElectionDefinition::parse_eml(xml, EMLParsingMode::Strict).ok_with_errors();
        assert!(result.is_err());
    }

    #[test]
    fn test_invalid_election_missing_number_of_seats() {
        let xml = include_str!(
            "../../test-files/election_definition/eml110a_invalid_election_missing_number_of_seats.eml.xml"
        );

        let result = ElectionDefinition::parse_eml(xml, EMLParsingMode::Strict).ok_with_errors();
        assert!(result.is_err());
    }

    #[test]
    fn test_invalid_election_missing_preference_threshold() {
        let xml = include_str!(
            "../../test-files/election_definition/eml110a_invalid_election_missing_preference_threshold.eml.xml"
        );

        let result = ElectionDefinition::parse_eml(xml, EMLParsingMode::Strict).ok_with_errors();
        assert!(result.is_err());
    }

    #[test]
    fn test_invalid_election_missing_subcategory() {
        let xml = include_str!(
            "../../test-files/election_definition/eml110a_invalid_election_missing_subcategory.eml.xml"
        );

        let result = ElectionDefinition::parse_eml(xml, EMLParsingMode::Strict).ok_with_errors();
        assert!(result.is_err());
    }

    #[test]
    fn test_invalid_election_number_of_seats() {
        let xml = include_str!(
            "../../test-files/election_definition/eml110a_invalid_election_number_of_seats.eml.xml"
        );

        let result = ElectionDefinition::parse_eml(xml, EMLParsingMode::Strict).ok_with_errors();
        assert!(result.is_err());
    }

    #[test]
    fn test_invalid_election_subcategory() {
        let xml = include_str!(
            "../../test-files/election_definition/eml110a_invalid_election_subcategory.eml.xml"
        );

        let result = ElectionDefinition::parse_eml(xml, EMLParsingMode::Strict).ok_with_errors();
        assert!(result.is_err());
    }

    #[test]
    fn test_invalid_election_category_version() {
        // KC is invalid for legacy EML_NL version without a specified version number
        let xml = include_str!(
            "../../test-files/election_definition/eml110a_invalid_election_category_version.eml.xml"
        );

        let result = ElectionDefinition::parse_eml(xml, EMLParsingMode::Strict).ok_with_errors();
        let err = result.expect_err("expected parsing to fail");
        assert!(err.to_string().contains("KC"));
        assert!(err.to_string().contains("1.2.2"));
    }

    #[test]
    fn test_valid_election_category_version() {
        // The same document as the previous test but with for version 1.3, for which KC is valid
        let xml = include_str!(
            "../../test-files/election_definition/eml110a_valid_election_category_version.eml.xml"
        );

        let result = ElectionDefinition::parse_eml(xml, EMLParsingMode::Strict).ok_with_errors();
        assert!(result.is_ok());
    }

    #[test]
    fn test_invalid_election_voting_method() {
        let xml = include_str!(
            "../../test-files/election_definition/eml110a_invalid_election_voting_method.eml.xml"
        );

        let result = ElectionDefinition::parse_eml(xml, EMLParsingMode::Strict).ok_with_errors();
        assert!(result.is_err());
    }
}