fasters 0.4.0

FIX & FAST (FIX Adapted for STreaming) in pure Rust.
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
//! Access to FIX Dictionary reference and message specifications.

use crate::app::Version;
use quickfix::{ParseDictionaryError, QuickFixReader};
use std::collections::HashMap;
use std::io;
use std::ops::Range;

/// Value for the field `MsgType (35)`.
#[derive(Copy, Debug, Clone, PartialEq, Eq, Hash)]
pub struct MsgType(u16);

impl MsgType {
    pub fn write(&self, writer: &mut impl io::Write) -> io::Result<()> {
        let bytes = self.0.to_be_bytes();
        for byte in bytes.iter() {
            writer.write(&[*byte])?;
        }
        Ok(())
    }
}

impl From<&[u8]> for MsgType {
    fn from(bytes: &[u8]) -> Self {
        debug_assert!(bytes.len() <= std::mem::size_of::<u16>());
        let mut value: u16 = 0;
        for byte in bytes {
            value = (value << 8) + (*byte as u16);
        }
        MsgType(value)
    }
}

type InternalId = u32;

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum PKey {
    #[allow(dead_code)]
    Abbreviation(String),
    CategoryByName(String),
    ComponentByName(String),
    DatatypeByName(String),
    FieldByTag(u32),
    FieldByName(String),
    MessageByName(String),
    MessageByMsgType(MsgType),
}

#[derive(Copy, Debug, Clone, PartialEq, Eq, Hash)]
enum PKeyRef<'a> {
    Abbreviation(&'a str),
    CategoryByName(&'a str),
    ComponentByName(&'a str),
    DatatypeByName(&'a str),
    FieldByTag(u32),
    FieldByName(&'a str),
    MessageByName(&'a str),
    MessageByMsgType(MsgType),
}

impl PKey {
    fn as_ref<'a>(&'a self) -> PKeyRef<'a> {
        match self {
            PKey::Abbreviation(s) => PKeyRef::Abbreviation(s.as_str()),
            PKey::CategoryByName(s) => PKeyRef::CategoryByName(s.as_str()),
            PKey::ComponentByName(s) => PKeyRef::ComponentByName(s.as_str()),
            PKey::DatatypeByName(s) => PKeyRef::DatatypeByName(s.as_str()),
            PKey::FieldByTag(t) => PKeyRef::FieldByTag(*t),
            PKey::FieldByName(s) => PKeyRef::FieldByName(s.as_str()),
            PKey::MessageByName(s) => PKeyRef::MessageByName(s.as_str()),
            PKey::MessageByMsgType(t) => PKeyRef::MessageByMsgType(*t),
        }
    }
}

trait SymbolTableIndex {
    fn to_key(&self) -> PKeyRef;
}

impl SymbolTableIndex for PKey {
    fn to_key(&self) -> PKeyRef {
        self.as_ref()
    }
}

impl<'a> SymbolTableIndex for PKeyRef<'a> {
    fn to_key(&self) -> PKeyRef {
        *self
    }
}

impl<'a> std::hash::Hash for dyn SymbolTableIndex + 'a {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.to_key().hash(state);
    }
}

impl<'a> std::borrow::Borrow<dyn SymbolTableIndex + 'a> for PKey {
    fn borrow(&self) -> &(dyn SymbolTableIndex + 'a) {
        self
    }
}

impl<'a> Eq for dyn SymbolTableIndex + 'a {}

impl<'a> PartialEq for dyn SymbolTableIndex + 'a {
    fn eq(&self, other: &dyn SymbolTableIndex) -> bool {
        self.to_key() == other.to_key()
    }
}

/// Specification of the application layer of FIX Protocol.
///
/// All FIX Dictionaries have a version string which MUST be unique and
/// established out-of-band between involved parties.
///
/// N.B. The FIX Protocol mandates separation of concerns between session and
/// application protocol only for FIX 5.0 and subsequent versions. All FIX
/// Dictionaries with older versions will also contain information about session
/// layer.
#[derive(Clone, Debug)]
pub struct Dictionary {
    version: String,
    symbol_table: HashMap<PKey, InternalId>,
    abbreviations: Vec<AbbreviatonData>,
    data_types: Vec<DatatypeData>,
    fields: Vec<FieldData>,
    components: Vec<ComponentData>,
    messages: Vec<MessageData>,
    layout_items: Vec<LayoutItemData>,
    categories: Vec<CategoryData>,
    header: Vec<FieldData>,
}

impl Dictionary {
    /// Creates a new empty FIX Dictionary named `version`.
    ///
    /// # Examples
    ///
    /// ```
    /// use fasters::Dictionary;
    /// let dict = Dictionary::new("FIX.foobar");
    /// ```
    pub fn new<S: ToString>(version: S) -> Self {
        Dictionary {
            version: version.to_string(),
            symbol_table: HashMap::new(),
            abbreviations: Vec::new(),
            data_types: Vec::new(),
            fields: Vec::new(),
            components: Vec::new(),
            messages: Vec::new(),
            layout_items: Vec::new(),
            categories: vec![],
            header: Vec::new(),
        }
    }

    /// Creates a new [`Dictionary`] according to the specification of
    /// `version`.
    pub fn from_version(version: Version) -> Self {
        Dictionary::save_definition_spec(version.get_quickfix_spec()).unwrap()
    }

    /// Creates a new empty FIX Dictionary with `FIX.???` as its version string.
    pub fn empty() -> Self {
        Self::new("FIX.???")
    }

    /// Returns the version string associated with this [`Dictionary`] (e.g.
    /// `FIXT.1.1`, `FIX.4.2`).
    ///
    /// ```
    /// use fasters::Dictionary;
    /// use fasters::app::Version;
    ///
    /// let dict = Dictionary::from_version(Version::Fix44);
    /// assert_eq!(dict.get_version(), "FIX.4.4");
    /// ```
    pub fn get_version(&self) -> &str {
        self.version.as_str()
    }

    fn symbol(&self, pkey: PKeyRef) -> Option<&u32> {
        self.symbol_table.get(&pkey as &dyn SymbolTableIndex)
    }

    /// Return the known abbreviation for `term` -if any- according to the
    /// documentation of this FIX Dictionary.
    pub fn abbreviation_for<S: AsRef<str>>(&self, term: S) -> Option<Abbreviation> {
        self.symbol(PKeyRef::Abbreviation(term.as_ref()))
            .map(|iid| self.abbreviations.get(*iid as usize).unwrap())
            .map(move |data| Abbreviation(self, data))
    }

    /// Returns the [`Message`] associated with `name`, if any.
    ///
    /// ```
    /// use fasters::Dictionary;
    /// use fasters::app::Version;
    ///
    /// let dict = Dictionary::from_version(Version::Fix44);
    ///
    /// let msg1 = dict.get_message_by_name("Heartbeat").unwrap();
    /// let msg2 = dict.get_message_by_msg_type("0").unwrap();
    /// assert_eq!(msg1.name(), msg2.name());
    /// ```
    pub fn get_message_by_name<S: AsRef<str>>(&self, name: S) -> Option<Message> {
        self.symbol(PKeyRef::MessageByName(name.as_ref()))
            .map(|iid| self.messages.get(*iid as usize).unwrap())
            .map(|data| Message(self, data))
    }

    pub fn get_message_by_msg_type<S: AsRef<str>>(&self, key: S) -> Option<Message> {
        self.symbol(PKeyRef::MessageByMsgType(MsgType::from(
            key.as_ref().as_bytes(),
        )))
        .map(|iid| self.messages.get(*iid as usize).unwrap())
        .map(|data| Message(self, data))
    }

    /// Returns the [`Component`] named `name`, if any.
    pub fn get_component<S: AsRef<str>>(&self, name: S) -> Option<Component> {
        self.symbol(PKeyRef::ComponentByName(name.as_ref()))
            .map(|iid| self.components.get(*iid as usize).unwrap())
            .map(|data| Component(self, data))
    }

    /// Returns an [`Iterator`] over this [`Dictionary`]'s components. Items are in
    /// no particular order.
    pub fn components(&self) -> impl Iterator<Item = Component> {
        self.components
            .iter()
            .map(move |data| Component(&self, data))
    }

    /// Returns an [`Iterator`] over this [`Dictionary`]'s messages. Items are in
    /// no particular order.
    ///
    /// ```
    /// use fasters::Dictionary;
    /// use fasters::app::Version;
    ///
    /// let dict = Dictionary::from_version(Version::Fix44);
    /// let msg = dict.messages().find(|m| m.name() == "MarketDataRequest");
    /// assert_eq!(msg.unwrap().msg_type(), "V");
    /// ```
    pub fn messages(&self) -> impl Iterator<Item = Message> {
        self.messages.iter().map(move |data| Message(&self, data))
    }

    /// Returns an [`Iterator`] over this [`Dictionary`]'s categories. Items are
    /// in no particular order.
    pub fn categories(&self) -> impl Iterator<Item = Category> {
        self.categories
            .iter()
            .map(move |data| Category(&self, data))
    }

    /// Returns the [`Field`] associated with `tag`, if any.
    ///
    /// ```
    /// use fasters::Dictionary;
    /// use fasters::app::Version;
    ///
    /// let dict = Dictionary::from_version(Version::Fix44);
    ///
    /// let field1 = dict.get_field(112).unwrap();
    /// let field2 = dict.get_field_by_name("TestReqID").unwrap();
    /// assert_eq!(field1.name(), field2.name());
    /// ```
    pub fn get_field(&self, tag: u32) -> Option<Field> {
        self.symbol(PKeyRef::FieldByTag(tag))
            .map(|iid| self.fields.get(*iid as usize).unwrap())
            .map(|data| Field(self, data))
    }

    /// Returns the [`Field`] named `name`, if any.
    pub fn get_field_by_name<S: AsRef<str>>(&self, name: S) -> Option<Field> {
        self.symbol(PKeyRef::FieldByName(name.as_ref()))
            .map(|iid| self.fields.get(*iid as usize).unwrap())
            .map(|data| Field(self, data))
    }

    /// Attempts to read a QuickFIX-style specification file and convert it into
    /// a [`Dictionary`].
    pub fn save_definition_spec<S: AsRef<str>>(input: S) -> Result<Self, ParseDictionaryError> {
        let xml_document = roxmltree::Document::parse(input.as_ref()).unwrap();
        QuickFixReader::new(&xml_document)
    }
}

/// Enumeration type for all base types in the FIX specification.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum BaseType {
    Int,
    Float,
    Char,
    String,
    Data,
}

#[derive(Clone, Debug)]
struct CategoryData {
    /// **Primary key**. A string uniquely identifying this category.
    name: String,
    /// The FIXML file name for a Category.
    fixml_filename: String,
}

/// A [`Category`] is a collection of loosely related FIX messages or components
/// all belonging to the same [`Section`].
#[derive(Clone, Debug)]
pub struct Category<'a>(&'a Dictionary, &'a CategoryData);

#[derive(Clone, Debug)]
struct AbbreviatonData {
    abbreviation: String,
    is_last: bool,
}

/// An [`Abbreviation`] is a standardized abbreviated form for a specific word,
/// pattern, or name. Abbreviation data is mostly meant for documentation
/// purposes, but in general it can have other uses as well, e.g. FIXML field
/// naming.
#[derive(Debug)]
pub struct Abbreviation<'a>(&'a Dictionary, &'a AbbreviatonData);

impl<'a> Abbreviation<'a> {
    /// Returns the full term (non-abbreviated) associated with `self`.
    pub fn term(&self) -> &str {
        self.1.abbreviation.as_str()
    }
}

#[derive(Clone, Debug)]
struct ComponentData {
    /// **Primary key.** The unique integer identifier of this component
    /// type.
    id: usize,
    component_type: ComponentType,
    layout_items_iid_range: Range<u32>,
    category_iid: InternalId,
    /// The human readable name of the component.
    name: String,
    /// The name for this component when used in an XML context.
    abbr_name: Option<String>,
}

/// A [`Component`] is an ordered collection of fields and/or other components.
/// There are two kinds of components: (1) common blocks and (2) repeating
/// groups. Common blocks are merely commonly reused sequences of the same
/// fields/components
/// which are given names for simplicity, i.e. they serve as "macros". Repeating
/// groups, on the other hand, are components which can appear zero or more times
/// inside FIX messages (or other components, for that matter).
#[derive(Clone, Debug)]
pub struct Component<'a>(&'a Dictionary, &'a ComponentData);

impl<'a> Component<'a> {
    /// Returns the unique numberic ID of `self`.
    pub fn id(&self) -> u32 {
        self.1.id as u32
    }

    /// Returns the name of `self`. The name of every [`Component`] is unique
    /// across a [`Dictionary`].
    pub fn name(&self) -> &str {
        self.1.name.as_str()
    }

    /// Returns the [`Category`] to which `self` belongs.
    pub fn category(&self) -> Category {
        let data = self.0.categories.get(self.1.category_iid as usize).unwrap();
        Category(self.0, data)
    }

    pub fn items(&self) -> impl Iterator<Item = LayoutItem> {
        let start = self.1.layout_items_iid_range.start as usize;
        let end = self.1.layout_items_iid_range.end as usize;
        self.0.layout_items[start..end]
            .iter()
            .map(move |data| LayoutItem(self.0, data))
    }

    /// Checks whether `field` appears in the definition of `self` and returns
    /// `true` if it does, `false` otherwise.
    pub fn contains_field(&self, field: &Field) -> bool {
        self.items().any(|layout_item| {
            if let LayoutItemKind::Field(f) = layout_item.kind() {
                f.tag() == field.tag()
            } else {
                false
            }
        })
    }
}

// FIXME: this is FIXML-specific stuff.
#[derive(Clone, Debug, PartialEq)]
#[allow(dead_code)]
pub enum ComponentType {
    BlockRepeating,
    Block,
    ImplicitBlockRepeating,
    ImplicitBlock,
    OptimisedBlockRepeating,
    OptimisedImplicitBlockRepeating,
    XMLDataBlock,
    Message,
}

#[derive(Clone, Debug, PartialEq)]
struct DatatypeData {
    /// **Primary key.** Identifier of the datatype.
    pub name: String,
    /// Base type from which this type is derived.
    base_type: Option<String>,
    /// Human readable description of this Datatype.
    description: String,
    /// A string that contains examples values for a datatype
    examples: Vec<String>,
    // TODO: 'XML'.
}

#[derive(Debug)]
pub struct Datatype<'a>(&'a Dictionary, &'a DatatypeData);

impl<'a> Datatype<'a> {
    pub fn name(&self) -> &str {
        self.1.name.as_str()
    }

    pub fn basetype(&self) -> BaseType {
        str_to_basetype(self.1.name.as_str())
    }
}

#[derive(Clone, Debug, PartialEq)]
pub struct Enum {}

/// A field is identified by a unique tag number and a name. Each field in a
/// message is associated with a value.
#[derive(Clone, Debug)]
struct FieldData {
    /// A human readable string representing the name of the field.
    name: String,
    /// **Primary key.** A positive integer representing the unique
    /// identifier for this field type.
    tag: u32,
    /// The datatype of the field.
    data_type_iid: InternalId,
    /// The associated data field. If given, this field represents the length of
    /// the referenced data field
    associated_data_tag: Option<usize>,
    value_restrictions: Option<Vec<FieldEnumData>>,
    /// Abbreviated form of the Name, typically to specify the element name when
    /// the field is used in an XML message. Can be overridden by BaseCategory /
    /// BaseCategoryAbbrName.
    abbr_name: Option<String>,
    /// Specifies the base message category when field is used in an XML message.
    base_category_id: Option<usize>,
    /// If BaseCategory is specified, this is the XML element identifier to use
    /// for this field, overriding AbbrName.
    base_category_abbr_name: Option<String>,
    /// Indicates whether the field is required in an XML message.
    required: bool,
    description: Option<String>,
}

#[derive(Clone, Debug)]
struct FieldEnumData {
    value: String,
    description: String,
}

#[derive(Debug)]
pub struct FieldEnum<'a>(&'a Dictionary, &'a FieldEnumData);

impl<'a> FieldEnum<'a> {
    pub fn value(&self) -> &str {
        &self.1.value[..]
    }

    pub fn description(&self) -> &str {
        &self.1.description[..]
    }
}

/// A field is the most granular message structure abstraction. It carries a
/// specific business meaning as described by the FIX specifications. The data
/// domain of a [`Field`] is either a [`Datatype`] or a "code set", i.e.
/// enumeration.
#[derive(Debug)]
pub struct Field<'a>(&'a Dictionary, &'a FieldData);

fn str_to_basetype(s: &str) -> BaseType {
    match s {
        "STRING" => BaseType::String,
        "UTCTIMESTAMP" => BaseType::String,
        "CHAR" => BaseType::Char,
        "INT" => BaseType::Int,
        "LENGTH" => BaseType::Int,
        "SEQNUM" => BaseType::Int,
        "FLOAT" => BaseType::Float,
        "DATA" => BaseType::Data,
        _ => BaseType::Char, // FIXME
    }
}

impl<'a> Field<'a> {
    pub fn doc_url_onixs(&self, version: &str) -> String {
        let v = match version {
            "FIX.4.0" => "4.0",
            "FIX.4.1" => "4.1",
            "FIX.4.2" => "4.2",
            "FIX.4.3" => "4.3",
            "FIX.4.4" => "4.4",
            "FIX.5.0" => "5.0",
            "FIX.5.0SP1" => "5.0.SP1",
            "FIX.5.0SP2" => "5.0.SP2",
            "FIXT.1.1" => "FIXT.1.1",
            s => s,
        };
        let mut url = "https://www.onixs.biz/fix-dictionary/".to_string();
        url.push_str(v);
        url.push_str("/tagNum_");
        url.push_str(self.1.tag.to_string().as_str());
        url.push_str(".html");
        url
    }

    /// Returns the [`BaseType`] of `self`.
    pub fn basetype(&self) -> BaseType {
        self.data_type().basetype()
    }

    /// Returns the name of `self`. Field names are unique across each FIX
    /// [`Dictionary`].
    pub fn name(&self) -> &str {
        self.1.name.as_str()
    }

    /// Returns the numeric tag of `self`. Field tags are unique across each FIX
    /// [`Dictionary`].
    pub fn tag(&self) -> u32 {
        self.1.tag
    }

    pub fn enums(&self) -> Option<impl Iterator<Item = FieldEnum>> {
        self.1
            .value_restrictions
            .as_ref()
            .map(move |v| v.iter().map(move |f| FieldEnum(self.0, f)))
    }

    /// Returns the [`Datatype`] of `self`.
    pub fn data_type(&self) -> Datatype {
        let data = self
            .0
            .data_types
            .get(self.1.data_type_iid as usize)
            .unwrap();
        Datatype(self.0, data)
    }
}

#[derive(Clone, Debug, PartialEq)]
pub struct FieldRef {
    pub name: String,
    pub required: char,
}

#[derive(Clone, Debug)]
enum LayoutItemKindData {
    Component(u32),
    Group(Range<u32>),
    Field(u32),
}

#[derive(Clone, Debug)]
struct LayoutItemData {
    required: bool,
    kind: LayoutItemKindData,
}

#[derive(Clone, Debug)]
pub struct LayoutItem<'a>(&'a Dictionary, &'a LayoutItemData);

/// The kind of element contained in a [`Message`].
#[derive(Debug)]
pub enum LayoutItemKind<'a> {
    Component(Component<'a>),
    Group(),
    Field(Field<'a>),
}

impl<'a> LayoutItem<'a> {
    /// Returns `true` if `self` is required in order to have a valid definition
    /// of its parent container, `false` otherwise.
    pub fn required(&self) -> bool {
        self.1.required
    }

    pub fn kind(&self) -> LayoutItemKind {
        match &self.1.kind {
            LayoutItemKindData::Component(n) => LayoutItemKind::Component(Component(
                self.0,
                self.0.components.get(*n as usize).unwrap(),
            )),
            LayoutItemKindData::Group(_range) => {
                LayoutItemKind::Group() // FIXME
            }
            LayoutItemKindData::Field(n) => {
                LayoutItemKind::Field(Field(self.0, self.0.fields.get(*n as usize).unwrap()))
            }
        }
    }

    pub fn tag_text(&self) -> &str {
        match &self.1.kind {
            LayoutItemKindData::Component(n) => {
                self.0.components.get(*n as usize).unwrap().name.as_str()
            }
            LayoutItemKindData::Group(_range) => "",
            LayoutItemKindData::Field(n) => self.0.fields.get(*n as usize).unwrap().name.as_str(),
        }
    }
}

#[derive(Clone, Debug)]
struct MessageData {
    /// The unique integer identifier of this message type.
    component_id: u32,
    /// **Primary key**. The unique character identifier of this message
    /// type; used literally in FIX messages.
    msg_type: String,
    /// The name of this message type.
    name: String,
    /// Identifier of the category to which this message belongs.
    category_iid: InternalId,
    /// Identifier of the section to which this message belongs.
    section_id: String,
    layout_items: Range<InternalId>,
    /// The abbreviated name of this message, when used in an XML context.
    abbr_name: Option<String>,
    /// A boolean used to indicate if the message is to be generated as part
    /// of FIXML.
    required: bool,
    description: String,
    elaboration: Option<String>,
}

/// A [`Message`] is a unit of information sent on the wire between
/// counterparties. Every [`Message`] is composed of fields and/or components.
#[derive(Debug)]
pub struct Message<'a>(&'a Dictionary, &'a MessageData);

impl<'a> Message<'a> {
    /// Returns the human-readable name of `self`.
    pub fn name(&self) -> &str {
        self.1.name.as_str()
    }

    /// Returns the message type of `self`.
    pub fn msg_type(&self) -> &str {
        self.1.msg_type.as_str()
    }

    /// Returns the description associated with `self`.
    pub fn description(&self) -> &str {
        &self.1.description
    }

    /// Returns the component ID of `self`.
    pub fn component_id(&self) -> u32 {
        self.1.component_id
    }

    pub fn layout(&self) -> impl Iterator<Item = LayoutItem> {
        let start = self.1.layout_items.start as usize;
        let end = self.1.layout_items.end as usize;
        self.0.layout_items[start..end]
            .iter()
            .map(move |data| LayoutItem(self.0, data))
    }
}

#[derive(Clone, Debug, PartialEq)]
pub struct MsgContent {
    component_id: usize,
    pub tag_text: String,
    pub reqd: char,
}

/// A [`Section`] is a collection of many [`Components`]-s. It has no practical
/// effect on encoding and decoding of FIX data and it's only used for
/// documentation and human readability.
#[derive(Clone, Debug, PartialEq)]
pub struct Section {}

#[derive(Clone, Debug, PartialEq)]
pub struct Value {
    value_enum: String,
    description: Option<String>,
}

mod quickfix {
    use super::*;

    fn add_datatype(dict: &mut Dictionary, datatype: DatatypeData) {
        let iid = dict.data_types.len();
        let name = datatype.name.clone();
        dict.data_types.push(datatype);
        dict.symbol_table
            .insert(PKey::DatatypeByName(name), iid as u32);
    }

    fn add_all_datatypes(dict: &mut Dictionary) {
        // Add all datatypes to the dictionary. QuickFix definition files
        // don't have datatypes.
        add_datatype(
            dict,
            DatatypeData {
                name: "STRING".to_string(),
                base_type: Some("string".to_string()),
                description: String::new(),
                examples: vec![],
            },
        );
        add_datatype(
            dict,
            DatatypeData {
                name: "INT".to_string(),
                base_type: Some("int".to_string()),
                description: String::new(),
                examples: vec![],
            },
        );
        add_datatype(
            dict,
            DatatypeData {
                name: "CHAR".to_string(),
                base_type: Some("char".to_string()),
                description: String::new(),
                examples: vec![],
            },
        );
    }

    pub(crate) struct QuickFixReader<'a> {
        node_with_header: roxmltree::Node<'a, 'a>,
        node_with_trailer: roxmltree::Node<'a, 'a>,
        node_with_components: roxmltree::Node<'a, 'a>,
        node_with_messages: roxmltree::Node<'a, 'a>,
        node_with_fields: roxmltree::Node<'a, 'a>,
        dict: Dictionary,
    }

    impl<'a> QuickFixReader<'a> {
        pub fn new(
            xml_document: &'a roxmltree::Document<'a>,
        ) -> Result<Dictionary, ParseDictionaryError> {
            let mut reader = Self::empty(&xml_document)?;
            add_all_datatypes(&mut reader.dict);
            for child in reader.node_with_fields.children() {
                if child.is_element() {
                    reader.add_field(child);
                }
            }
            for child in reader.node_with_components.children() {
                if child.is_element() {
                    reader.add_component(child);
                }
            }
            for child in reader.node_with_messages.children() {
                if child.is_element() {
                    reader.add_message(child);
                }
            }
            reader.add_component_with_name(reader.node_with_header, "StandardHeader");
            reader.add_component_with_name(reader.node_with_trailer, "StandardTrailer");
            Ok(reader.dict)
        }

        fn empty(xml_document: &'a roxmltree::Document<'a>) -> Result<Self, ParseDictionaryError> {
            let root = xml_document.root_element();
            let find_tagged_child = |tag: &str| {
                root.children()
                    .find(|n| n.has_tag_name(tag))
                    .ok_or_else(|| {
                        ParseDictionaryError::InvalidData(format!("<{}> tag not found", tag))
                    })
            };
            let version_type = root
                .attribute("type")
                .ok_or(ParseDictionaryError::InvalidData(
                    "No version attribute.".to_string(),
                ))?;
            let version_major =
                root.attribute("major")
                    .ok_or(ParseDictionaryError::InvalidData(
                        "No majorr version attribute.".to_string(),
                    ))?;
            let version_minor =
                root.attribute("minor")
                    .ok_or(ParseDictionaryError::InvalidData(
                        "No minor version attribute.".to_string(),
                    ))?;
            let version = format!("{}.{}.{}", version_type, version_major, version_minor);
            Ok(QuickFixReader {
                node_with_header: find_tagged_child("header")?,
                node_with_trailer: find_tagged_child("trailer")?,
                node_with_messages: find_tagged_child("messages")?,
                node_with_components: find_tagged_child("components")?,
                node_with_fields: find_tagged_child("fields")?,
                dict: Dictionary::new(version),
            })
        }

        fn add_field(&mut self, node: roxmltree::Node) {
            let iid = self.dict.fields.len() as u32;
            let field = FieldData::definition_from_node(&mut self.dict, node);
            self.dict
                .symbol_table
                .insert(PKey::FieldByName(field.name.clone()), iid);
            self.dict
                .symbol_table
                .insert(PKey::FieldByTag(field.tag as u32), iid);
            self.dict.fields.push(field);
        }

        fn add_component_with_name<S: AsRef<str>>(&mut self, node: roxmltree::Node, name: S) {
            let iid = self.dict.components.len();
            let component =
                ComponentData::definition_from_node_with_name(&mut self.dict, node, name.as_ref());
            self.dict
                .symbol_table
                .insert(PKey::ComponentByName(name.as_ref().to_string()), iid as u32);
            self.dict.components.push(component);
        }

        fn add_component(&mut self, node: roxmltree::Node) {
            let iid = self.dict.components.len();
            let component = ComponentData::definition_from_node(&mut self.dict, node);
            self.dict
                .symbol_table
                .insert(PKey::ComponentByName(component.name.clone()), iid as u32);
            self.dict.components.push(component);
        }

        fn add_message(&mut self, node: roxmltree::Node) {
            let iid = self.dict.messages.len() as u32;
            let message = MessageData::definition_from_node(&mut self.dict, node);
            self.dict
                .symbol_table
                .insert(PKey::MessageByName(message.name.clone()), iid);
            self.dict.symbol_table.insert(
                PKey::MessageByMsgType(MsgType::from(message.msg_type.as_bytes())),
                iid,
            );
            self.dict.messages.push(message);
        }
    }

    impl ComponentData {
        fn definition_from_node(dict: &mut Dictionary, node: roxmltree::Node) -> Self {
            debug_assert_eq!(node.tag_name().name(), "component");
            let name = node.attribute("name").unwrap().to_string();
            Self::definition_from_node_with_name(dict, node, name)
        }

        fn definition_from_node_with_name<S: AsRef<str>>(
            dict: &mut Dictionary,
            node: roxmltree::Node,
            name: S,
        ) -> Self {
            let layout_start = dict.layout_items.len() as u32;
            for child in node.children() {
                if child.is_element() {
                    // We don't need IID's because we're dealing with ranges.
                    let item = LayoutItemData::save_definition(dict, child);
                    dict.layout_items.push(item);
                }
            }
            let layout_end = dict.layout_items.len() as u32;
            ComponentData {
                id: 0,
                component_type: ComponentType::Block,
                layout_items_iid_range: layout_start..layout_end,
                category_iid: 0, // FIXME
                name: name.as_ref().to_string(),
                abbr_name: None,
            }
        }

        fn get_or_create_iid_from_ref(dict: &mut Dictionary, node: roxmltree::Node) -> InternalId {
            debug_assert_eq!(node.tag_name().name(), "component");
            let name = node.attribute("name").unwrap();
            match dict.symbol(PKeyRef::ComponentByName(name)) {
                Some(x) => *x,
                None => {
                    let iid = dict.data_types.len() as u32;
                    let data = ComponentData {
                        id: 0,
                        component_type: ComponentType::Block,
                        layout_items_iid_range: 0..0,
                        name: name.to_string(),
                        category_iid: 0, // FIXME
                        abbr_name: None,
                    };
                    dict.components.push(data);
                    dict.symbol_table
                        .insert(PKey::ComponentByName(name.to_string()), iid);
                    iid
                }
            }
        }
    }

    fn value_restrictions_from_node(
        node: roxmltree::Node,
        _datatype: InternalId,
    ) -> Option<Vec<FieldEnumData>> {
        let mut values = Vec::new();
        for child in node.children() {
            if child.is_element() {
                let variant = child.attribute("enum").unwrap().to_string();
                let description = child.attribute("description").unwrap().to_string();
                let enum_value = FieldEnumData {
                    value: variant,
                    description,
                };
                values.push(enum_value);
            }
        }
        if values.len() == 0 {
            None
        } else {
            Some(values)
        }
    }

    impl FieldData {
        fn definition_from_node(dict: &mut Dictionary, node: roxmltree::Node) -> Self {
            debug_assert_eq!(node.tag_name().name(), "field");
            let data_type_iid = DatatypeData::get_or_create_iid_from_ref(dict, node);
            let value_restrictions = value_restrictions_from_node(node, data_type_iid);
            FieldData {
                name: node.attribute("name").unwrap().to_string(),
                tag: node.attribute("number").unwrap().parse().unwrap(),
                data_type_iid: data_type_iid,
                associated_data_tag: None,
                value_restrictions,
                required: true,
                abbr_name: None,
                base_category_abbr_name: None,
                base_category_id: None,
                description: None,
            }
        }
    }

    impl DatatypeData {
        fn get_or_create_iid_from_ref(dict: &mut Dictionary, node: roxmltree::Node) -> InternalId {
            // References should only happen at <field> tags.
            debug_assert_eq!(node.tag_name().name(), "field");
            let name = node.attribute("type").unwrap();
            match dict.symbol(PKeyRef::DatatypeByName(name)) {
                Some(x) => *x,
                None => {
                    let iid = dict.data_types.len() as u32;
                    let data = DatatypeData {
                        name: name.to_string(),
                        description: String::new(),
                        examples: Vec::new(),
                        base_type: None,
                    };
                    dict.data_types.push(data);
                    dict.symbol_table
                        .insert(PKey::DatatypeByName(name.to_string()), iid);
                    iid
                }
            }
        }
    }

    impl LayoutItemData {
        fn save_definition(dict: &mut Dictionary, node: roxmltree::Node) -> Self {
            // This processing step requires on fields being already present in
            // the dictionary.
            debug_assert_ne!(dict.fields.len(), 0);
            let name = node.attribute("name").unwrap();
            let required = node.attribute("required").unwrap() == "Y";
            let tag = node.tag_name().name();
            let kind = match tag {
                "field" => {
                    let field_iid = dict.symbol(PKeyRef::FieldByName(name)).unwrap();
                    LayoutItemKindData::Field(*field_iid)
                }
                "component" => {
                    // Components may *not* be already present.
                    let component_iid = ComponentData::get_or_create_iid_from_ref(dict, node);
                    LayoutItemKindData::Component(component_iid)
                }
                "group" => {
                    let start_range = dict.layout_items.len() as u32;
                    let items = node
                        .children()
                        .filter(|n| n.is_element())
                        .map(|child| LayoutItemData::save_definition(dict, child))
                        .count();
                    LayoutItemKindData::Group(start_range..(start_range + items as u32))
                }
                _ => {
                    panic!("Invalid tag!")
                }
            };
            LayoutItemData { required, kind }
        }
    }

    impl MessageData {
        fn definition_from_node(dict: &mut Dictionary, node: roxmltree::Node) -> Self {
            debug_assert_eq!(node.tag_name().name(), "message");
            let category_iid = CategoryData::get_or_create_iid_from_ref(dict, node);
            let layout_start = dict.layout_items.len() as u32;
            for child in node.children() {
                if child.is_element() {
                    // We don't need IID's because we're dealing with ranges.
                    let data = LayoutItemData::save_definition(dict, child);
                    dict.layout_items.push(data);
                }
            }
            let layout_end = dict.layout_items.len() as u32;
            MessageData {
                name: node.attribute("name").unwrap().to_string(),
                msg_type: node.attribute("msgtype").unwrap().to_string(),
                component_id: 0,
                category_iid,
                section_id: String::new(),
                layout_items: layout_start..layout_end,
                abbr_name: None,
                required: true,
                elaboration: None,
                description: String::new(),
            }
        }
    }

    impl CategoryData {
        fn get_or_create_iid_from_ref(dict: &mut Dictionary, node: roxmltree::Node) -> InternalId {
            debug_assert_eq!(node.tag_name().name(), "message");
            let name = node.attribute("msgcat").unwrap();
            match dict.symbol(PKeyRef::CategoryByName(name)) {
                Some(x) => *x,
                None => {
                    let iid = dict.categories.len() as u32;
                    dict.categories.push(CategoryData {
                        name: name.to_string(),
                        fixml_filename: String::new(),
                    });
                    dict.symbol_table
                        .insert(PKey::CategoryByName(name.to_string()), iid);
                    iid
                }
            }
        }
    }

    /// The error type that can arise when decoding a QuickFIX Dictionary.
    #[derive(Clone, Debug)]
    pub enum ParseDictionaryError {
        InvalidFormat,
        InvalidData(String),
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::app::Version;
    use quickcheck::QuickCheck;
    use std::convert::TryInto;

    #[test]
    fn msg_type_conversion() {
        fn prop(val: u16) -> bool {
            let bytes = val.to_le_bytes();
            let msg_type = MsgType::from(&bytes[..]);
            let mut buffer = vec![0, 0];
            msg_type.write(&mut &mut buffer[..]).unwrap();
            val == u16::from_le_bytes((&buffer[..]).try_into().unwrap())
        }
        QuickCheck::new()
            .tests(1000)
            .quickcheck(prop as fn(u16) -> bool)
    }

    #[test]
    fn fixt11_quickfix_is_ok() {
        let dict = Dictionary::from_version(Version::Fixt11);
        let msg_heartbeat = dict.get_message_by_name("Heartbeat").unwrap();
        assert_eq!(msg_heartbeat.msg_type(), "0");
        assert_eq!(msg_heartbeat.name(), "Heartbeat".to_string());
        assert!(msg_heartbeat.layout().any(|c| {
            if let LayoutItemKind::Field(f) = c.kind() {
                f.name() == "TestReqID"
            } else {
                false
            }
        }));
    }

    #[test]
    fn dictionary_save_definition_spec_is_ok() {
        for version in Version::all() {
            Dictionary::from_version(version);
        }
    }

    #[test]
    fn fix44_field_28_has_three_variants() {
        let dict = Dictionary::from_version(Version::Fix44);
        let field_28 = dict.get_field(28).unwrap();
        assert_eq!(field_28.name(), "IOITransType");
        assert_eq!(field_28.enums().unwrap().count(), 3);
    }

    #[test]
    fn fix44_field_36_has_no_variants() {
        let dict = Dictionary::from_version(Version::Fix44);
        let field_36 = dict.get_field(36).unwrap();
        assert_eq!(field_36.name(), "NewSeqNo");
        assert!(field_36.enums().is_none());
    }

    #[test]
    fn fix44_field_167_has_eucorp_variant() {
        let dict = Dictionary::from_version(Version::Fix44);
        let field_167 = dict.get_field(167).unwrap();
        assert_eq!(field_167.name(), "SecurityType");
        assert!(field_167.enums().unwrap().any(|e| e.value() == "EUCORP"));
    }
}