asterix_parser 0.1.1

Playground do Protocolo ASTERIX
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
pub mod acas_and_fl_status;
pub mod acas_res_report;
pub mod aircraft_address;
pub mod aircraft_id;
pub mod bds_register_data;
pub mod data_source_id;
pub mod flight_level; 
pub mod height_3d;
pub mod mode_1_code;
pub mod mode_1_confidence;
pub mod mode_2_code;
pub mod mode_2_confidence;
pub mod mode_3a_code;
pub mod mode_3a_confidence;
pub mod mode_c_code_conf;
pub mod positon_cart_coord;
pub mod positon_polar_coord;
pub mod radar_plot_charac;
pub mod radial_dopp_speed;
pub mod time_of_day;
pub mod tgt_report_desc;
pub mod track_number;
pub mod track_status;
pub mod track_quality;
pub mod velocity_polar_coord;
pub mod warning_errors;

use std::any::Any;
use std::ops::Range;
use std::{any::TypeId, collections::BTreeMap, fmt};
use bitvec::prelude::*;
use strum_macros::{AsRefStr, EnumString};

use crate::asterix::{category::CategoryIndex, message::AsterixMessageParseError};
use crate::asterix::uap::{common, UAPEntryLength};
use super::datatypes::{AsterixAttribute, AttributeProperties};
use bitvec::{order::Msb0, vec::BitVec};

pub mod constants {
    pub const DATA_ITEM_PREFIX: char = 'I';
}

pub enum DataItemTypes {
    DataSourceId { datasourceid: DataSourceId },
    TargetReportDesc { targetreportdesc: TargetReportDesc },
    WarnErrorConditions { warnerrorconditions: WarnErrorConditions },
    PositionPolarCoord { positionpolarcoord: PositionPolarCoord },
    PositionCartesianCoord { positioncartesiancoord: PositionCartesianCoord },
    Mode2CodeOctal { mode2codeoctal: Mode2CodeOctal },
    Mode1CodeOctal { mode1codeoctal: Mode1CodeOctal },
    Mode2CodeConfid { mode2codeconfid: Mode2CodeConfid },
    Mode1CodeConfid { mode1codeconfid: Mode1CodeConfid },
    Mode3ACodeOctal { mode3acodeoctal: Mode3ACodeOctal },
    Mode3AConfid { mode3aconfid: Mode3AConfid },
    FlightLevelBin { flightlevelbin: FlightLevelBin },
    ModeCCodeAndConfid { modeccodeandconfid: ModeCCodeAndConfid },
    Height3DRadar { height3dradar: Height3DRadar },
    RadialDopplerSpeed { radialdopplerspeed: RadialDopplerSpeed },
    RadarPlotCharac { radarplotcharac: RadarPlotCharac },
    TimeOfDday { timeofdday: TimeOfDday },
    TrackNumber { tracknumber: TrackNumber },
    TrackStatus { trackstatus: TrackStatus },
    TrackVelocPolar { trackvelocpolar: TrackVelocPolar },
    TrackQuality { trackquality: TrackQuality },
    AircraftAddr { aircraftaddr: AircraftAddr },
    CommACASAndFlitghtStatus { commacasandflitghtstatus: CommACASAndFlitghtStatus },
    ACASResolReport { acasresolreport: ACASResolReport },
    AircraftId { aircraftid: AircraftId },
    ModeSMBData { modesmbdata: ModeSMBData },
    SPF { spf: SPF },
    REF { sref: REF }
}

#[derive(AsRefStr, Clone, Copy, Debug, PartialEq, EnumString)]
pub enum DataItemIndex {
    _010,
    _020,
    _030,
    _040,
    _042,
    _050,
    _055,
    _060,
    _065,
    _070,
    _080,
    _090,
    _100,
    _110,
    _120,
    _130,
    _140,
    _161,
    _170,
    _200,
    _210,
    _220,
    _230,
    _240,
    _250,
    _260,
    _REF,
    _SPF
}

#[derive(Clone)]
pub struct DataItem {
    pub category: CategoryIndex,
    pub data_item_index: DataItemIndex,
    pub content: String,
    pub type_id: TypeId, 
    pub length: UAPEntryLength 
}

impl DataItem {
    pub fn get_name(&self) -> String {
        fmt::format(
            format_args!("{}{}{}",
            constants::DATA_ITEM_PREFIX,
            self.category.as_str(),
            self.data_item_index.as_ref()))
    }

    pub fn describe(&self) -> String {
        fmt::format(
             format_args!("{}{}{}: {:<50} : length: {:<15}",
             constants::DATA_ITEM_PREFIX,
             self.category.as_str(),
             self.data_item_index.as_ref(),
             self.content,
             self.length.as_ref()))
    }
}

pub trait DataItemStore {
    fn set_octets(octets: &Vec<u8>);
    fn get_octets() -> Vec<u8>;
    fn get_size_in_octets() -> usize;
    fn get_attribute_def() -> BTreeMap<u8, AttributeProperties>;
}

pub trait TDataItem {
    fn get_attributes() -> Vec<AsterixAttribute>;
    fn get_length(octets: &Vec<u8>, start_index: usize) -> Result<usize, AsterixMessageParseError>;
}


pub struct DataSourceId;

impl TDataItem for DataSourceId {
    fn get_attributes() -> Vec<AsterixAttribute> {
        data_source_id::get_attributes!()
    }
    
    fn get_length(_octets: &Vec<u8>, _start_index: usize) -> Result<usize, AsterixMessageParseError> {
        Ok(2) // Fixed length
    }
}

pub struct TargetReportDesc;

impl TDataItem for TargetReportDesc {
    fn get_attributes() -> Vec<AsterixAttribute> {
       tgt_report_desc::get_attributes!()
    }
    
    fn get_length(octets: &Vec<u8>, start_index: usize) -> Result<usize, AsterixMessageParseError> {
        let len =common::get_extensible_data_item_length!(octets, start_index);
        len
    }
}

pub struct WarnErrorConditions;

impl TDataItem for WarnErrorConditions {
    fn get_attributes() -> Vec<AsterixAttribute> {
       warning_errors::get_attributes!()
    }
    
    fn get_length(octets: &Vec<u8>, start_index: usize) -> Result<usize, AsterixMessageParseError> {
        common::get_extensible_data_item_length!(octets, start_index)
    }
}

pub struct PositionPolarCoord;

impl TDataItem for PositionPolarCoord {
    fn get_attributes() -> Vec<AsterixAttribute> {
        positon_polar_coord::get_attributes!()
    }
    
    fn get_length(_octets: &Vec<u8>, _start_index: usize) -> Result<usize, AsterixMessageParseError> {
        Ok(4)
    }
}

pub struct PositionCartesianCoord;

impl TDataItem for PositionCartesianCoord {
    fn get_attributes() -> Vec<AsterixAttribute> {
        positon_cart_coord::get_attributes!()
    }
    
    fn get_length(_octets: &Vec<u8>, _start_index: usize) -> Result<usize, AsterixMessageParseError> {
        Ok(4) // Fixed length
    }
}

pub struct Mode2CodeOctal;

impl TDataItem for Mode2CodeOctal {
    fn get_attributes() -> Vec<AsterixAttribute> {
        mode_1_code::get_attributes!()
    }
    
    fn get_length(_octets: &Vec<u8>, _start_index: usize) -> Result<usize, AsterixMessageParseError> {
        Ok(2) // Fixed length
    }
}

pub struct Mode1CodeOctal;

impl TDataItem for Mode1CodeOctal {
    fn get_attributes() -> Vec<AsterixAttribute> {
        mode_2_code::get_attributes!()
    }
    
    fn get_length(_octets: &Vec<u8>, _start_index: usize) -> Result<usize, AsterixMessageParseError> {
        Ok(1) // Fixed length
    }
}

pub struct Mode2CodeConfid;

impl TDataItem for Mode2CodeConfid {
    fn get_attributes() -> Vec<AsterixAttribute> {
        mode_2_confidence::get_attributes!()
    }
    
    fn get_length(_octets: &Vec<u8>, _start_index: usize) -> Result<usize, AsterixMessageParseError> {
        Ok(2) // Fixed length
    }
}

pub struct Mode1CodeConfid;

impl TDataItem for Mode1CodeConfid {
    fn get_attributes() -> Vec<AsterixAttribute> {
        mode_1_confidence::get_attributes!()
    }
    
    fn get_length(_octets: &Vec<u8>, _start_index: usize) -> Result<usize, AsterixMessageParseError> {
        Ok(1)
    }
}

pub struct Mode3ACodeOctal;

impl TDataItem for Mode3ACodeOctal {
    fn get_attributes() -> Vec<AsterixAttribute> {
       mode_3a_code::get_attributes!()
    }
    
    fn get_length(_octets: &Vec<u8>, _start_index: usize) -> Result<usize, AsterixMessageParseError> {
        Ok(2) // Fixed length
    }
}

pub struct Mode3AConfid;

impl TDataItem for Mode3AConfid {
    fn get_attributes() -> Vec<AsterixAttribute> {
        mode_3a_confidence::get_attributes!()
    }
    
    fn get_length(_octets: &Vec<u8>, _start_index: usize) -> Result<usize, AsterixMessageParseError> {
        Ok(2) // Fixed length
    }
}

pub struct FlightLevelBin;

impl TDataItem for FlightLevelBin {
    fn get_attributes() -> Vec<AsterixAttribute> {
       flight_level::get_attributes!()
    }
    
    fn get_length(_octets: &Vec<u8>, _start_index: usize) -> Result<usize, AsterixMessageParseError> {
        Ok(2) // Fixed length
    }
}

pub struct ModeCCodeAndConfid;

impl TDataItem for ModeCCodeAndConfid {
    fn get_attributes() -> Vec<AsterixAttribute> {
       mode_c_code_conf::get_attributes!()
    }
    
    fn get_length(_octets: &Vec<u8>, _start_index: usize) -> Result<usize, AsterixMessageParseError> {
        Ok(4) // Fixed length
    }
}

pub struct Height3DRadar;

impl TDataItem for Height3DRadar {
    fn get_attributes() -> Vec<AsterixAttribute> {
       height_3d::get_attributes!()
    }
    
    fn get_length(_octets: &Vec<u8>, _start_index: usize) -> Result<usize, AsterixMessageParseError> {
        Ok(2) // Fixed length
    }
}

pub struct RadialDopplerSpeed;

impl TDataItem for RadialDopplerSpeed {
    fn get_attributes() -> Vec<AsterixAttribute> {
       radial_dopp_speed::get_attributes!()
    }
    
    fn get_length(octets: &Vec<u8>, start_index: usize) -> Result<usize, AsterixMessageParseError> {
        common::get_extensible_data_item_length!(octets, start_index)
    }
}

pub struct RadarPlotCharac;

impl TDataItem for RadarPlotCharac {
    fn get_attributes() -> Vec<AsterixAttribute> {
        radar_plot_charac::get_attributes!()
    }
    
    fn get_length(octets: &Vec<u8>, start_index: usize) -> Result<usize, AsterixMessageParseError> {
        use bitvec::prelude::*;

        let mut len = 1 as usize;
        // todo: fix length calculation
        let mut current_index = start_index;
        let mut octet = octets[current_index];
        loop {
            let octet_bits = octet.view_bits::<Msb0>().to_bitvec();
            let is_fx_set = octet_bits[0];
            if is_fx_set {
                len = len + 1;
                current_index = current_index + 1;
                octet = octets[current_index];
            } else {
                break;
            }
        }

        Ok(len)
    }
}

pub struct TimeOfDday;

impl TDataItem for TimeOfDday {
    fn get_attributes() -> Vec<AsterixAttribute> {
        time_of_day::get_attributes!()
    }
    
    fn get_length(_octets: &Vec<u8>, _start_index: usize) -> Result<usize, AsterixMessageParseError> {
        Ok(3) // Fixed Length
    }
}

pub struct TrackNumber;

impl TDataItem for TrackNumber {
    fn get_attributes() -> Vec<AsterixAttribute> {
        track_number::get_attributes!()
    }
    
    fn get_length(_octets: &Vec<u8>, _start_index: usize) -> Result<usize, AsterixMessageParseError> {
        Ok(2) // Fixed length
    }
}

pub struct TrackStatus;

impl TDataItem for TrackStatus {
    fn get_attributes() -> Vec<AsterixAttribute> {
        track_status::get_attributes!()
    }
    
    fn get_length(octets: &Vec<u8>, start_index: usize) -> Result<usize, AsterixMessageParseError> {
        common::get_extensible_data_item_length!(octets, start_index)
    }
}

pub struct TrackVelocPolar;

impl TDataItem for TrackVelocPolar {
    fn get_attributes() -> Vec<AsterixAttribute> {
        velocity_polar_coord::get_attributes!()
    }
    
    fn get_length(_octets: &Vec<u8>, _start_index: usize) -> Result<usize, AsterixMessageParseError> {
        Ok(4) // Fixed length
    }
}

pub struct TrackQuality;

impl TDataItem for TrackQuality {
    fn get_attributes() -> Vec<AsterixAttribute> {
        track_quality::get_attributes!()
    }
    
    fn get_length(_octets: &Vec<u8>, _start_index: usize) -> Result<usize, AsterixMessageParseError> {
        Ok(4) // Fixed length
    }
}

pub struct AircraftAddr;

impl TDataItem for AircraftAddr {
    fn get_attributes() -> Vec<AsterixAttribute> {
        aircraft_address::get_attributes!()
    }
    
    fn get_length(_octets: &Vec<u8>, _start_index: usize) -> Result<usize, AsterixMessageParseError> {
       Ok(3) // Fixed length
    }
}

pub struct CommACASAndFlitghtStatus;

impl TDataItem for CommACASAndFlitghtStatus {
    fn get_attributes() -> Vec<AsterixAttribute> {
        acas_and_fl_status::get_attributes!()
    }
    
    fn get_length(_octets: &Vec<u8>, _start_index: usize) -> Result<usize, AsterixMessageParseError> {
        Ok(2) // Fixed length
    }
}

pub struct ACASResolReport;

impl TDataItem for ACASResolReport {
    fn get_attributes() -> Vec<AsterixAttribute> {
        acas_res_report::get_attributes!()
    }
    
    fn get_length(_octets: &Vec<u8>, _start_index: usize) -> Result<usize, AsterixMessageParseError> {
        Ok(7) // Fixed length
    }
}

pub struct AircraftId;

impl TDataItem for AircraftId {
    fn get_attributes() -> Vec<AsterixAttribute> {
        aircraft_id::get_attributes!()
    }
    
    fn get_length(_octets: &Vec<u8>, _start_index: usize) -> Result<usize, AsterixMessageParseError> {
        Ok(6) // Fixed length
    }
}

    
pub struct ModeSMBData;

impl TDataItem for ModeSMBData {
    fn get_attributes() -> Vec<AsterixAttribute> {
        bds_register_data::get_attributes!()
    }

    fn get_length(octets: &Vec<u8>, start_index: usize) -> Result<usize, AsterixMessageParseError> {
        let attributes = ModeSMBData::get_attributes();
        let len = match common::get_repetitive_data_item_length!(octets, start_index, &attributes) {
        // let len = match get_repetitive(octets, start_index, attributes) {
            Ok(s) => s,
            Err(e) => return Err(e),
        };

        Ok(len)
        /*
        let mut len = attributes[0].octets_len as usize; // First attribute is repetitive byte length

        let len_octets = octets[0..len].iter().clone().as_slice();        
        let repetitive_factor = match find_repetitive_len(len_octets) {
            Ok(s) => s,
            Err(e) => return Err(e),
        };

        let mut variable_len = 0 as usize;
        let mut last_field = 1 as u8;   
        for attribute in attributes {
            if attribute.field !=  last_field {
                variable_len = variable_len + attribute.octets_len as usize;
            }
        }
        len = len + variable_len * repetitive_factor as usize;

        Ok(len)  */
    }
}

/*
fn find_repetitive_len(len_octets: &[u8]) -> Result<usize, AsterixMessageParseError> {
    if len_octets.len() < 0 || len_octets.len() > 2 {
        return Err(AsterixMessageParseError::InvalidRepetitiveFieldLength { size: len_octets.len() })
    }

    let mut len_octets_array: [u8; 2] = [0, 0];
    if len_octets.len() == 1  {
        len_octets_array[1] - len_octets[0];
    } else {
        len_octets_array[0] = len_octets[0];
        len_octets_array[1] = len_octets[1];
    }

    let len = u16::from_le_bytes(len_octets_array);
    Ok(len as usize)
}
 */

// todo: not defined yet
pub struct SPF;

impl TDataItem for SPF {
    fn get_attributes() -> Vec<AsterixAttribute> {
        // todo: implement if needed
        Vec::new()
    }
    
    fn get_length(_octets: &Vec<u8>, _start_index: usize) -> Result<usize, AsterixMessageParseError> {
        Ok(0) // todo: implement if needed
    }
}

// todo: not defined yet
pub struct REF;

impl TDataItem for REF {
    fn get_attributes() -> Vec<AsterixAttribute> {
        // todo: implement if needed
        Vec::new()
    }
    
    fn get_length(_octets: &Vec<u8>, _start_index: usize) -> Result<usize, AsterixMessageParseError> {
        Ok(0) // todo: implement if needed
    }
}

pub struct ConsumedDataItem {
    pub length: usize,
    pub octets: Vec<u8>
}

pub fn get_data_item(data_item: &DataItem, message_octets: &Vec<u8>, data_start_index: usize)  
->  Result<ConsumedDataItem, AsterixMessageParseError> {
    let data_item_length = 
        match get_data_item_length(data_item.type_id, message_octets, data_start_index) {
            Some(s) => s,
            None => return  Err(AsterixMessageParseError::CouldNotRetrieveLength { dataitem: data_item.get_name() })
    };

    let range = data_start_index .. (data_start_index + data_item_length);
    let octets = message_octets[range].iter().cloned().collect::<Vec<u8>>();
    Ok(ConsumedDataItem {
        length: data_item_length,
        octets: octets
    })
}

pub fn get_data_item_length(type_id: TypeId, octets: &Vec<u8>, start_index: usize) ->  Option<usize> {
    if type_id == TypeId::of::<DataSourceId>() {return Some(DataSourceId::get_length(octets, start_index).unwrap()); }
    if type_id == TypeId::of::<TimeOfDday>() { return Some(TimeOfDday::get_length(octets, start_index).unwrap()); }
    if type_id == TypeId::of::<TargetReportDesc>() { return Some(TargetReportDesc::get_length(octets, start_index).unwrap()); }
    if type_id == TypeId::of::<PositionPolarCoord>() { return Some(PositionPolarCoord::get_length(octets, start_index).unwrap()); }
    if type_id == TypeId::of::<Mode3ACodeOctal>() { return Some(Mode3ACodeOctal::get_length(octets, start_index).unwrap()); }
    if type_id == TypeId::of::<FlightLevelBin>() { return Some(FlightLevelBin::get_length(octets, start_index).unwrap()); }
    if type_id == TypeId::of::<RadarPlotCharac>() { return Some(RadarPlotCharac::get_length(octets, start_index).unwrap()); }
    if type_id == TypeId::of::<AircraftAddr>() { return Some(AircraftAddr::get_length(octets, start_index).unwrap()); }
    if type_id == TypeId::of::<AircraftId>() { return Some(AircraftId::get_length(octets, start_index).unwrap()); }
    if type_id == TypeId::of::<ModeSMBData>() { return Some(ModeSMBData::get_length(octets, start_index).unwrap()); }
    if type_id == TypeId::of::<TrackNumber>() { return Some(TrackNumber::get_length(octets, start_index).unwrap()); }
    if type_id == TypeId::of::<PositionCartesianCoord>() { return Some(PositionCartesianCoord::get_length(octets, start_index).unwrap()); }
    if type_id == TypeId::of::<TrackVelocPolar>() { return Some(TrackVelocPolar::get_length(octets, start_index).unwrap()); }
    if type_id == TypeId::of::<TrackStatus>() { return Some(TrackStatus::get_length(octets, start_index).unwrap()); }
    if type_id == TypeId::of::<TrackQuality>() { return Some(TrackQuality::get_length(octets, start_index).unwrap()); }
    if type_id == TypeId::of::<WarnErrorConditions>() { return Some(WarnErrorConditions::get_length(octets, start_index).unwrap()); }
    if type_id == TypeId::of::<Mode3AConfid>() { return Some(Mode3AConfid::get_length(octets, start_index).unwrap()); }
    if type_id == TypeId::of::<ModeCCodeAndConfid>() { return Some(ModeCCodeAndConfid::get_length(octets, start_index).unwrap()); }
    if type_id == TypeId::of::<Height3DRadar>() { return Some(Height3DRadar::get_length(octets, start_index).unwrap()); }
    if type_id == TypeId::of::<RadialDopplerSpeed>() { return Some(RadialDopplerSpeed::get_length(octets, start_index).unwrap()); }
    if type_id == TypeId::of::<CommACASAndFlitghtStatus>() { return Some(CommACASAndFlitghtStatus::get_length(octets, start_index).unwrap()); }
    if type_id == TypeId::of::<ACASResolReport>() { return Some(ACASResolReport::get_length(octets, start_index).unwrap()); }
    if type_id == TypeId::of::<Mode1CodeOctal>() { return Some(Mode1CodeOctal::get_length(octets, start_index).unwrap()); }
    if type_id == TypeId::of::<Mode2CodeOctal>() { return Some(Mode2CodeOctal::get_length(octets, start_index).unwrap()); }
    if type_id == TypeId::of::<Mode1CodeConfid>() { return Some(Mode1CodeConfid::get_length(octets, start_index).unwrap()); }
    if type_id == TypeId::of::<Mode2CodeConfid>() { return Some(Mode2CodeConfid::get_length(octets, start_index).unwrap()); }
    // if type_id == TypeId::of::<SPF>() { return Some(SPF::get_length(octets, start_index)); }
    // if type_id == TypeId::of::<REF>() { return Some(REF::get_length(octets, start_index)); }
    None
}

pub fn get_data_item_attributes(type_id: TypeId) ->  Option<Vec<AsterixAttribute>> {
    if type_id == TypeId::of::<DataSourceId>() {return Some(DataSourceId::get_attributes()); }
    if type_id == TypeId::of::<TimeOfDday>() { return Some(TimeOfDday::get_attributes()); }
    if type_id == TypeId::of::<TargetReportDesc>() { return Some(TargetReportDesc::get_attributes()); }
    if type_id == TypeId::of::<PositionPolarCoord>() { return Some(PositionPolarCoord::get_attributes()); }
    if type_id == TypeId::of::<Mode3ACodeOctal>() { return Some(Mode3ACodeOctal::get_attributes()); }
    if type_id == TypeId::of::<FlightLevelBin>() { return Some(FlightLevelBin::get_attributes()); }
    if type_id == TypeId::of::<RadarPlotCharac>() { return Some(RadarPlotCharac::get_attributes()); }
    if type_id == TypeId::of::<AircraftAddr>() { return Some(AircraftAddr::get_attributes()); }
    if type_id == TypeId::of::<AircraftId>() { return Some(AircraftId::get_attributes()); }
    if type_id == TypeId::of::<ModeSMBData>() { return Some(ModeSMBData::get_attributes()); }
    if type_id == TypeId::of::<TrackNumber>() { return Some(TrackNumber::get_attributes()); }
    if type_id == TypeId::of::<PositionCartesianCoord>() { return Some(PositionCartesianCoord::get_attributes()); }
    if type_id == TypeId::of::<TrackVelocPolar>() { return Some(TrackVelocPolar::get_attributes()); }
    if type_id == TypeId::of::<TrackStatus>() { return Some(TrackStatus::get_attributes()); }
    if type_id == TypeId::of::<TrackQuality>() { return Some(TrackQuality::get_attributes()); }
    if type_id == TypeId::of::<WarnErrorConditions>() { return Some(WarnErrorConditions::get_attributes()); }
    if type_id == TypeId::of::<Mode3AConfid>() { return Some(Mode3AConfid::get_attributes()); }
    if type_id == TypeId::of::<ModeCCodeAndConfid>() { return Some(ModeCCodeAndConfid::get_attributes()); }
    if type_id == TypeId::of::<Height3DRadar>() { return Some(Height3DRadar::get_attributes()); }
    if type_id == TypeId::of::<RadialDopplerSpeed>() { return Some(RadialDopplerSpeed::get_attributes()); }
    if type_id == TypeId::of::<CommACASAndFlitghtStatus>() { return Some(CommACASAndFlitghtStatus::get_attributes()); }
    if type_id == TypeId::of::<ACASResolReport>() { return Some(ACASResolReport::get_attributes()); }
    if type_id == TypeId::of::<Mode1CodeOctal>() { return Some(Mode1CodeOctal::get_attributes()); }
    if type_id == TypeId::of::<Mode2CodeOctal>() { return Some(Mode2CodeOctal::get_attributes()); }
    if type_id == TypeId::of::<Mode1CodeConfid>() { return Some(Mode1CodeConfid::get_attributes()); }
    if type_id == TypeId::of::<Mode2CodeConfid>() { return Some(Mode2CodeConfid::get_attributes()); }
    // if type_id == TypeId::of::<SPF>() { return Some(SPF::get_attributes()); }
    // if type_id == TypeId::of::<REF>() { return Some(REF::get_attributes()); }
    None
}


/* pub fn is_bit_n_set(octet:u8, bit_number: u8) -> bool {
    let exp = 8 - bit_number;
    let mask = 2_i32.pow(exp as u32) as u8;
    let is_bit_set = octet & mask != 0 ;
    is_bit_set
}
*/

pub fn get_attributes_from_dataitem(data_item: &DataItem, consumed_data: &ConsumedDataItem) 
    -> Option<BTreeMap<String, AttributeProperties>> {
    let attributes = get_data_item_attributes(data_item.type_id).unwrap();
    let data_item_prefix = data_item.get_name();
    let mut attribute_properties = BTreeMap::<String, AttributeProperties>::new();
    let mut last_consumed_octet = 0 as usize;
    let mut last_len: usize;
    let mut last_field = attributes[0].field;
    let mut len: usize = attributes[0].octets_len as usize;
    let mut range: Range<usize> = last_consumed_octet..last_consumed_octet+len;
    let mut attribute_octets= consumed_data.octets[range].iter().clone().as_slice();
    for attribute in &attributes { 
        if last_field != attribute.field {
            last_field = attribute.field;
            last_len = len;
            len = attribute.octets_len as usize;
            last_consumed_octet = last_consumed_octet + last_len;    
            if data_item.length.type_id() == (UAPEntryLength::Variable { size_first: 1 }).type_id() && 
               consumed_data.octets.len() < (last_consumed_octet + len) {
                // optional data_item extension fields not set
                break;
            }
            range = last_consumed_octet..last_consumed_octet+len;            
            attribute_octets = consumed_data.octets[range].iter().clone().as_slice();  
        }
        let attribute_property = AttributeProperties {
            field_key: fmt::format(format_args!("{}_{}", &data_item_prefix, &attribute.name)),
            bits: get_attribute_bits(attribute, attribute_octets)
        }; 
        attribute_properties.insert(attribute_property.field_key.clone(), attribute_property);
    } 

    Some(attribute_properties)
}

pub fn get_msb_bits(octets: &[u8]) -> BitVec::<u8, Msb0> {
    let bv = (octets).view_bits::<Msb0>().to_bitvec();
    bv
}

pub fn get_lsb_bits(octets: &[u8]) -> BitVec::<u8, Lsb0> {
    let bv = (octets).view_bits::<Lsb0>().to_bitvec();
    bv
}

pub fn get_bitvec_subset_as_msb0(bv: &BitVec<u8,Msb0>, msb_index:usize , lsb_index: usize) -> BitVec::<u8, Msb0> {
    // let mut attribute_bits = BitVec::<u8, Msb0>::new();
    let range_begin = bv.len() - (msb_index);
    let range_end = bv.len() - (lsb_index - 1);

    let bv_slice = bv.as_bitslice();
    let attribute_slice = match bv_slice.get(range_begin .. range_end) {
        Some(bs) => bs,
        None => BitSlice::empty(),
    };

    let mut attribute_bits:BitVec::<u8, Msb0> = attribute_slice.to_bitvec();
    attribute_bits.reverse();
    attribute_bits
}

fn get_attribute_bits(attribute: &AsterixAttribute, attribute_octets: &[u8]) -> BitVec::<u8, Msb0> {
    let bv = get_msb_bits(attribute_octets);
    let attribute_bits = get_bitvec_subset_as_msb0(&bv, attribute.initial_bit as usize, attribute.final_bit as usize);
 
    attribute_bits
} 

pub fn get_expected_bits_from_u8_vec(vec_u8: &Vec<u8>) -> BitVec<u8, Msb0> {
    // let mut bitvec = (vec_u8).view_bits::<Msb0>().to_bitvec();
    let bitvec = get_msb_bits(vec_u8.as_slice());
    bitvec
}

pub mod tests {
    #[test]
    fn test_sac_bits() {
        use crate::asterix::uap::common::datatypes::AsterixAttribute;
        use crate::asterix::uap::common::datatypes::AttributeType;

        let attribute = AsterixAttribute::new(1, 1,  8, 1, "(SAC) System Area Code".to_string(), "sac".to_string(), AttributeType::UInt16);
        let attribute_octets = vec![0b00011001_u8];
        let bits = super::get_attribute_bits(&attribute, &attribute_octets);

        let octets_bits = super::get_expected_bits_from_u8_vec(&attribute_octets);
        let expected_bits = super::get_bitvec_subset_as_msb0(&octets_bits, 8, 1);
        assert_eq!(expected_bits, bits, "{} bits should match", attribute.name);
    }
    
    #[test]
    fn test_mode3a_code_bits() {
        use crate::asterix::uap::common::datatypes::AsterixAttribute;
        use crate::asterix::uap::common::datatypes::AttributeType;

        // Attributes from 1st field 
        let v_attr = AsterixAttribute::new(2, 1, 16, 16, "(V) Code Validated".to_string(), "validated".to_string(), AttributeType::Boolean);
        let g_attr = AsterixAttribute::new(2, 2, 15, 15, "(G) Garbled Code".to_string(), "garbled".to_string(), AttributeType::Boolean);
        let l_attr = AsterixAttribute::new(2, 3, 14, 14, "(L) Mode-3/A Code Absent".to_string(), "not_extracted".to_string(), AttributeType::Boolean);
        let m3_attr = AsterixAttribute::new(2, 4, 12, 1,  "Mode-3/A reply in octal".to_string(), "mode_3a_reply".to_string(), AttributeType::UInt16);

        let attribute_octets = vec![0b11100010_u8, 0b00000000];

        let octets_bits = super::get_expected_bits_from_u8_vec(&attribute_octets);

        let expected_bits = super::get_bitvec_subset_as_msb0(&octets_bits, 16, 16);
        let v_attr_bits = super::get_attribute_bits(&v_attr, &attribute_octets);
        assert_eq!(expected_bits, v_attr_bits, "{} bits should match", v_attr.name);

        let expected_bits = super::get_bitvec_subset_as_msb0(&octets_bits, 15, 15);
        let g_attr_bits = super::get_attribute_bits(&g_attr, &attribute_octets);
        assert_eq!(expected_bits, g_attr_bits, "{} bits should match", g_attr.name);

        let expected_bits = super::get_bitvec_subset_as_msb0(&octets_bits, 14, 14);
        let l_attr_bits = super::get_attribute_bits(&l_attr, &attribute_octets);
        assert_eq!(expected_bits, l_attr_bits, "{} bits should match", l_attr.name);

        let expected_bits = super::get_bitvec_subset_as_msb0(&octets_bits, 12, 1);
        let m3_attr_bits = super::get_attribute_bits(&m3_attr, &attribute_octets);
        assert_eq!(expected_bits, m3_attr_bits, "{} bits should match", m3_attr.name);
    }

        
    #[test]
    fn test_bits_retrieval() {
        use std::fmt;

        let trim_characters: &[_]  = &['[', ']', ' ', ','][..];
        let array_with_one_octet = [0b1111_0000 as u8];
        let array_with_two_octet = [0b1111_0000 as u8, 0b0000_1111];
        let lsb_bits = super::get_lsb_bits(&array_with_one_octet);
        // let lsb_slice = lsb_bits.as_bitslice();
        
        let bits_as_string = fmt::format(format_args!("{:b}", &lsb_bits)).replace(trim_characters, "");
        assert_eq!("00001111", bits_as_string);

        let lsb_bits = super::get_lsb_bits(&array_with_two_octet);

        let bits_as_string = fmt::format(format_args!("{:b}", &lsb_bits)).replace(trim_characters, "");
        assert_eq!("0000111111110000", bits_as_string);

        let msb_bits  = super::get_msb_bits(&array_with_one_octet);
        let bits_as_string = fmt::format(format_args!("{:b}", &msb_bits)).replace(trim_characters, "");
        assert_eq!("11110000", bits_as_string);

        let msb_bits  = super::get_msb_bits(&array_with_two_octet);
        let bits_as_string = fmt::format(format_args!("{:b}", &msb_bits)).replace(trim_characters, "");
        assert_eq!("1111000000001111", bits_as_string);
    }
}