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
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
/*
Copyright 2020 Timo Saarinen

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
use super::*;

// -------------------------------------------------------------------------------------------------
/// Result from function `decode_sentence`.
#[derive(Clone, Debug, PartialEq)]
pub enum ParsedSentence {
    /// The given sentence is only part of multi-sentence message and we need more data to
    /// create the actual result. State is stored in `NmeaStore` object.
    Incomplete,

    /// AIS VDM/VDO t1, t2, t3 and t18
    VesselDynamicData(VesselDynamicData),
    
    /// AIS VDM/VDO t5 and t24
    VesselStaticData(VesselStaticData),
    
    /// GGA
    Gga(PositionTimeSatelites),
    
    /// RMC
    Rmc(PositionVelocityTime),   
    
    /// GSA
    Gsa(PositionPrecision),         
    
    /// GSV
    Gsv(Vec<SatelliteInformation>),   
    
    /// VTG
    Vtg(VelocityMadeGood),
    
    /// GLL
    Gll(Position),
}

// -------------------------------------------------------------------------------------------------

/// AIS station based on talker id.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Station {
    BaseAisStation, // !AB
    DependentAisBaseStation, // !AD
    MobileAisStation, // !AI (the most common one)
    AidToNavigationAisStation, // !AN
    AisReceivingStation, // !AR
    LimitedBaseStation, // !AS
    AisTransmittingStation, // !AT
    RepeaterAisStation, // !AX
    Other, // !BS, !SA, etc.
}

impl Default for Station {
    fn default() -> Station {
        Station::Other
    }
}

// -------------------------------------------------------------------------------------------------

/// Navigation system, deptected from NMEA GNSS sentence prefix (e.g. $BDGGA).
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum NavigationSystem {
    /// Combination of several satellite systems
    Combination, // GNxxx
    
    /// American GPS
    Gps, // GPxxx
    
    /// Russian GLONASS
    Glonass, // GLxxx
    
    /// European Galileo
    Galileo, // GAxxx
    
    // Chinese BeiDou
    Beidou,  // BDxxx
    
    // Indian NavIC
    Navic,  // GIxxx
    
    // Japanese Qzss
    Qzss,  // QZxxx
    
    // Some other
    Other,
}

impl std::fmt::Display for NavigationSystem {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            NavigationSystem::Combination => { write!(f, "combination") }
            NavigationSystem::Gps => { write!(f, "GPS") }
            NavigationSystem::Glonass => { write!(f, "GLONASS") }
            NavigationSystem::Galileo => { write!(f, "Galileo") }
            NavigationSystem::Beidou => { write!(f, "BeiDou") }
            NavigationSystem::Navic => { write!(f, "Navic") }
            NavigationSystem::Qzss => { write!(f, "QZSS") }
            NavigationSystem::Other => { write!(f, "other") }
        }
        
    }
}


// -------------------------------------------------------------------------------------------------

/// AIVDM types 1, 2, 3 and 18
#[derive(Default, Clone, Debug, PartialEq)]
pub struct VesselDynamicData { 
    /// True if the data is about own vessel, false if about other.
    pub own_vessel: bool,

    /// AIS station type.
    pub station: Station,

    /// Class A or Class B
    pub ais_type: AisClass,

    /// User ID (30 bits)
    pub mmsi: u32,
    
    /// Navigation status
    pub nav_status: NavigationStatus,
    
    /// Accurate ROT_sensor (±0..708°/min) if available.
    pub rot: Option<f64>,
    
    /// ROT direction when turn is more than 5°/30s. Left = -1, center = 0, right = 1.
    pub rot_direction: Option<i8>,
    
    /// Speed over ground in knots
    pub sog_knots: Option<f64>,
    
    /// Position accuracy: true = high (<= 10 m), false = low (> 10 m)
    pub high_position_accuracy: bool,
    
    /// Latitude
    pub latitude: Option<f64>,

    /// Longitude
    pub longitude: Option<f64>,
    
    /// Course over ground
    pub cog: Option<f64>,
    
    /// True heading (0-359)
    pub heading_true: Option<f64>,
    
    /// Derived from UTC second (6 bits)
    pub timestamp_seconds: u8,

    /// Positioning system metadata (included in seconds in UTC timestamp)
    pub positioning_system_meta: Option<PositioningSystemMeta>,

    /// Special manoeuvre indicator. false = not engaged in special manoeuvre, 
    /// true = engaged in special manouvre.
    pub special_manoeuvre: Option<bool>,
    
    /// Riverine And Inland Navigation systems blue sign:
    /// RAIM (Receiver autonomous integrity monitoring) flag of electronic position 
    /// fixing device; false = RAIM not in use = default; true = RAIM in use
    pub raim_flag: bool,
    
    // Class B unit flag: false = Class B SOTDMA unit, true = Class B "CS" unit.    
    pub class_b_unit_flag: Option<bool>,

    /// Class B display: 
    /// false = No display available; not capable of displaying Message 12 and 14
    /// true  = Equipped with integrated display displaying Message 12 and 14 
    pub class_b_display: Option<bool>,

    /// Class B DSC: 
    /// false = Not equipped with DSC function 
    /// true  = Equipped with DSC function (dedicated or time-shared
    pub class_b_dsc: Option<bool>,

    /// Class B band flag: 
    /// false = Capable of operating over the upper 525 kHz band of the marine band 
    /// true  = Capable of operating over the whole marine band (irrelevant if 
    ///         “Class B Message 22 flag” is 0) 
    pub class_b_band_flag: Option<bool>,
    
    /// Class B Message 22 flag:
    /// false = No frequency management via Message 22 , operating on AIS1, AIS2 only 
    /// true  = Frequency management via Message 22
    pub class_b_msg22_flag: Option<bool>,
    
    /// Mode flag:
    /// false = Station operating in autonomous and continuous mode = default 
    /// true  = Station operating in assigned mode 
    pub class_b_mode_flag: Option<bool>,
    
    /// Communication state selector flag
    /// false = SOTDMA communication state follows 
    /// true  = ITDMA communication state follows (always “1” for Class-B “CS”)
    pub class_b_css_flag: Option<bool>,

    /// Communication state
    /// Diagnostic information for the radio system. 
    /// https://www.itu.int/dms_pubrec/itu-r/rec/m/R-REC-M.1371-1-200108-S!!PDF-E.pdf
    pub radio_status: u32,

}

/// AIS type, either Class A or Class B.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum AisClass {
    /// AIS class not known.
    Unknown,
    
    /// AIS class A.
    ClassA, // Message types 1, 2, 3, 5

    /// AIS class B.
    ClassB, // Message types 14, 18, 19, 24
}

impl Default for AisClass {
    fn default() -> AisClass {
        AisClass::Unknown
    }
}

impl std::fmt::Display for AisClass {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AisClass::Unknown => { write!(f, "?") }
            AisClass::ClassA => { write!(f, "A") }
            AisClass::ClassB => { write!(f, "B") }
        }
        
    }
}

/// Navigation status for VesselDynamicData
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum NavigationStatus {
    UnderWayUsingEngine, // 0
    AtAnchor, // 1
    NotUnderCommand, // 2
    RestrictedManoeuverability, // 3
    ConstrainedByDraught, // 4
    Moored, // 5
    Aground, // 6
    EngagedInFishing, // 7
    UnderWaySailing, // 8
    Reserved9, // 9, may be renamed in the future
    Reserved10, // 10, may be renamed in the future
    Reserved11, // 11, may be renamed in the future
    Reserved12, // 12, may be renamed in the future
    Reserved13, // 13, may be renamed in the future
    AisSartIsActive, // 14
    NotDefined, // 15

}
impl NavigationStatus {
    pub fn new(nav_status: u8) -> NavigationStatus {
        match nav_status {
            0  => { NavigationStatus::UnderWayUsingEngine },
            1  => { NavigationStatus::AtAnchor },
            2  => { NavigationStatus::NotUnderCommand },
            3  => { NavigationStatus::RestrictedManoeuverability },
            4  => { NavigationStatus::ConstrainedByDraught },
            5  => { NavigationStatus::Moored },
            6  => { NavigationStatus::Aground },
            7  => { NavigationStatus::EngagedInFishing },
            8  => { NavigationStatus::UnderWaySailing },
            9  => { NavigationStatus::Reserved9 },
            10 => { NavigationStatus::Reserved10 },
            11 => { NavigationStatus::Reserved11 },
            12 => { NavigationStatus::Reserved12 },
            13 => { NavigationStatus::Reserved13 },
            14 => { NavigationStatus::AisSartIsActive },
            15 => { NavigationStatus::NotDefined },
            _ => { NavigationStatus::NotDefined }
        }
    }
}

impl Default for NavigationStatus {
    fn default() -> NavigationStatus {
        NavigationStatus::NotDefined
    }
}

/// Location metadata about positioning system
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PositioningSystemMeta {
    Operative, // When timestamp second is 0-59
    ManualInputMode,
    DeadReckoningMode,
    Inoperative,
}

// -------------------------------------------------------------------------------------------------

/// AIVDM type 5 and 24
#[derive(Default, Clone, Debug, PartialEq)]
pub struct VesselStaticData { 
    /// True if the data is about own vessel, false if about other vessel.
    pub own_vessel: bool,

    /// Class A or Class B
    pub ais_type: AisClass,

    /// User ID (30 bits)
    pub mmsi: u32,

    /// AIS version indicator (2 bits)
    pub ais_version_indicator: u8,  
    
    /// IMO number (1-999999999; 30 bits).
    pub imo_number: Option<u32>,
    
    /// Call sign (42 bits)
    pub call_sign: Option<String>,
    
    /// Name (20 ASCII characters)
    pub name: Option<String>,
    
    /// Type of ship (first 4 of 8 bits)
    pub ship_type: ShipType,
    
    /// Type of ship and cargo (last 4 of 8 bits)
    pub cargo_type: CargoType,
    
    /// Class B Vendor ID 
    pub equipment_vendor_id: Option<String>,
    
    /// Class B unite model code
    pub equipment_model: Option<u8>,
    
    /// Class B serial number
    pub equipment_serial_number: Option<u32>,
    
    /// Overall dimension / reference for position A (9 bits)
    pub dimension_to_bow: Option<u16>,
    /// Overall dimension / reference for position B (9 bits)
    pub dimension_to_stern: Option<u16>,
    /// Overall dimension / reference for position C (6 bits)
    pub dimension_to_port: Option<u16>,
    /// Overall dimension / reference for position C (6 bits)
    pub dimension_to_starboard: Option<u16>,
    
    // Type of electronic position fixing device.
    pub position_fix_type: Option<PositionFixType>,
    
    /// ETA (20 bits)
    pub eta: Option<DateTime<Utc>>,
    
    /// Maximum present static draught in decimetres (1-255; 8 bits)
    pub draught10: Option<u8>,
    
    /// Destination (120 ASCII characters)
    pub destination: Option<String>,

    /// Class B mothership MMSI
    pub mothership_mmsi: Option<u32>,
}

/// Ship type derived from ship and cargo type field.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ShipType {
    NotAvailable, // 0
    Reserved1, // 1x
    WingInGround, // 2x
    Fishing, // 30
    Towing, // 31
    TowingLong, // 32; Towing: length exceeds 200m or breadth exceeds 25m
    DredgingOrUnderwaterOps, // 33
    DivingOps, // 34
    MilitaryOps, // 35
    Sailing, // 36
    PleasureCraft, // 37
    Reserved38, // 38
    Reserved39, // 39
    HighSpeedCraft, // 4x
    Pilot, // 50
    SearchAndRescue, // 51
    Tug, // 52
    PortTender, // 53
    AntiPollutionEquipment, // 54
    LawEnforcement, // 55
    SpareLocal56, // 56
    SpareLocal57, // 57
    MedicalTransport, // 58
    Noncombatant, // 59; Noncombatant ship according to RR Resolution No. 18
    Passenger, // 6x
    Cargo, // 7x
    Tanker, // 8x
    Other, // 9x
}

impl ShipType {
    pub fn new(raw: u8) -> ShipType {
        match raw {
            0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 => {
                ShipType::NotAvailable
            },
            10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 => {
                ShipType::Reserved1
            },
            20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 => {
                ShipType::WingInGround
            },

            30 => { ShipType::Fishing }
            31 => { ShipType::Towing }
            32 => { ShipType::TowingLong }
            33 => { ShipType::DredgingOrUnderwaterOps }
            34 => { ShipType::DivingOps }
            35 => { ShipType::MilitaryOps }
            36 => { ShipType::Sailing }
            37 => { ShipType::PleasureCraft }
            38 => { ShipType::Reserved38 }
            39 => { ShipType::Reserved39 }
            
            40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 => {
                ShipType::HighSpeedCraft
            },

            50 => { ShipType::Pilot }
            51 => { ShipType::SearchAndRescue }
            52 => { ShipType::Tug }
            53 => { ShipType::PortTender }
            54 => { ShipType::AntiPollutionEquipment }
            55 => { ShipType::LawEnforcement }
            56 => { ShipType::SpareLocal56 }
            57 => { ShipType::SpareLocal57 }
            58 => { ShipType::MedicalTransport }
            59 => { ShipType::Noncombatant }

            60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 => {
                ShipType::Passenger
            },
            70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 => {
                ShipType::Cargo
            },
            80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 => {
                ShipType::Cargo
            },
            90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 => {
                ShipType::Cargo
            },
            _ => {
                warn!("Unexpected ship and cargo type: {}", raw);
                ShipType::NotAvailable
            }
        }
    }
}

impl Default for ShipType {
    fn default() -> ShipType {
        ShipType::NotAvailable
    }
}


impl std::fmt::Display for ShipType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ShipType::NotAvailable => { write!(f,"(not available)") },
            ShipType::Reserved1 => { write!(f,"(reserved)") },
            ShipType::WingInGround => { write!(f,"wing in ground") },
            ShipType::Fishing => { write!(f,"fishing") },
            ShipType::Towing => { write!(f,"towing") },
            ShipType::TowingLong => { write!(f,"towing, long") },
            ShipType::DredgingOrUnderwaterOps => { write!(f,"dredging or underwater ops") },
            ShipType::DivingOps => { write!(f,"diving ops") },
            ShipType::MilitaryOps => { write!(f,"military ops") },
            ShipType::Sailing => { write!(f,"sailing") },
            ShipType::PleasureCraft => { write!(f,"pleasure craft") },
            ShipType::Reserved38 => { write!(f,"(reserved)") },
            ShipType::Reserved39 => { write!(f,"(reserved)") },
            ShipType::HighSpeedCraft => { write!(f,"high-speed craft") },
            ShipType::Pilot => { write!(f,"pilot") },
            ShipType::SearchAndRescue => { write!(f,"search and rescue") },
            ShipType::Tug => { write!(f,"tug") },
            ShipType::PortTender => { write!(f,"port tender") },
            ShipType::AntiPollutionEquipment => { write!(f,"anti-pollution equipment") },
            ShipType::LawEnforcement => { write!(f,"law enforcement") },
            ShipType::SpareLocal56 => { write!(f,"(local)") },
            ShipType::SpareLocal57 => { write!(f,"(local)") },
            ShipType::MedicalTransport => { write!(f,"medical transport") },
            ShipType::Noncombatant => { write!(f,"noncombatant") },
            ShipType::Passenger => { write!(f,"passenger") },
            ShipType::Cargo => { write!(f,"cargo") },
            ShipType::Tanker => { write!(f,"tanker") },
            ShipType::Other => { write!(f,"other") },
        }
    }
}

/// Cargo type derived from ship and cargo type field.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CargoType {
    Undefined, // x0
    HazardousCategoryA, // x1
    HazardousCategoryB, // x2
    HazardousCategoryC, // x3
    HazardousCategoryD, // x4
    Reserved5, // x5
    Reserved6, // x6
    Reserved7, // x7
    Reserved8, // x8
    Reserved9, // x9
}

impl CargoType {
    /// Construct a CargoType based on 8-bit NMEA identifier.
    pub fn new(raw: u8) -> CargoType {
        match raw {
            10 | 20 | 40 | 60 | 70 | 80 | 90 => {
                CargoType::Undefined
            },
            11 | 21 | 41 | 61 | 71 | 81 | 91 => {
                CargoType::HazardousCategoryA
            },
            12 | 22 | 42 | 62 | 72 | 82 | 92 => {
                CargoType::HazardousCategoryB
            },
            13 | 23 | 43 | 63 | 73 | 83 | 93 => {
                CargoType::HazardousCategoryC
            },
            14 | 24 | 44 | 64 | 74 | 84 | 94 => {
                CargoType::HazardousCategoryD
            },
            15 | 25 | 45 | 65 | 75 | 85 | 95 => {
                CargoType::Reserved5
            },
            16 | 26 | 46 | 66 | 76 | 86 | 96 => {
                CargoType::Reserved6
            },
            17 | 27 | 47 | 67 | 77 | 87 | 97 => {
                CargoType::Reserved7
            },
            18 | 28 | 48 | 68 | 78 | 88 | 98 => {
                CargoType::Reserved8
            },
            19 | 29 | 49 | 69 | 79 | 89 | 99 => {
                CargoType::Reserved9
            },
            _ => {
                warn!("Unexpected ship and cargo type: {}", raw);
                CargoType::Undefined
            }
        }
    }
}

impl std::fmt::Display for CargoType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CargoType::Undefined => { write!(f,"undefined") },
            CargoType::HazardousCategoryA => { write!(f,"hazardous category A") },
            CargoType::HazardousCategoryB => { write!(f,"hazardous category B") },
            CargoType::HazardousCategoryC => { write!(f,"hazardous category C") },
            CargoType::HazardousCategoryD => { write!(f,"hazardous category D") },
            CargoType::Reserved5 => { write!(f,"(reserved)") },
            CargoType::Reserved6 => { write!(f,"(reserved)") },
            CargoType::Reserved7 => { write!(f,"(reserved)") },
            CargoType::Reserved8 => { write!(f,"(reserved)") },
            CargoType::Reserved9 => { write!(f,"(reserved)") },
        }
    }
}

impl Default for CargoType {
    fn default() -> CargoType {
        CargoType::Undefined
    }
}


/// EPFD position fix types
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PositionFixType {
    Undefined, // 0
    GPS, // 1
    GLONASS, // 2
    GPSGLONASS, // 3
    LoranC, // 4
    Chayka, // 5
    IntegratedNavigationSystem, // 6
    Surveyed, // 7
    Galileo, // 8
}

impl PositionFixType {
    pub fn new(raw: u8) -> PositionFixType {
        match raw {
            0 => PositionFixType::Undefined,
            1 => PositionFixType::GPS,
            2 => PositionFixType::GLONASS,
            3 => PositionFixType::GPSGLONASS,
            4 => PositionFixType::LoranC,
            5 => PositionFixType::Chayka,
            6 => PositionFixType::IntegratedNavigationSystem,
            7 => PositionFixType::Surveyed,
            8 => PositionFixType::Galileo,
            _ => {
                warn!("Unrecognized position fix type: {}", raw);
                PositionFixType::Undefined
            },
        }
    }
}

impl VesselStaticData {
    /// Derive ISO 3166 country code from MID part of MMSI.
    pub fn country(&self)-> Option<&'static str> {
        match self.mmsi / 1000000 {
            // Mapping generated with mid-to-iso3166.py
            201 => Some("AL"), // Albania
            202 => Some("AD"), // Andorra
            203 => Some("AT"), // Austria
            204 => Some("PT"), // Portugal
            205 => Some("BE"), // Belgium
            206 => Some("BY"), // Belarus
            207 => Some("BG"), // Bulgaria
            208 => Some("VA"), // Vatican City State
            209 => Some("CY"), // Cyprus
            210 => Some("CY"), // Cyprus
            211 => Some("DE"), // Germany
            212 => Some("CY"), // Cyprus
            213 => Some("GE"), // Georgia
            214 => Some("MD"), // Moldova
            215 => Some("MT"), // Malta
            216 => Some("AM"), // Armenia
            218 => Some("DE"), // Germany
            219 => Some("DK"), // Denmark
            220 => Some("DK"), // Denmark
            224 => Some("ES"), // Spain
            225 => Some("ES"), // Spain
            226 => Some("FR"), // France
            227 => Some("FR"), // France
            228 => Some("FR"), // France
            229 => Some("MT"), // Malta
            230 => Some("FI"), // Finland
            231 => Some("FO"), // Faroe Islands
            232 => Some("GB"), // United Kingdom of Great Britain and Northern Ireland
            233 => Some("GB"), // United Kingdom of Great Britain and Northern Ireland
            234 => Some("GB"), // United Kingdom of Great Britain and Northern Ireland
            235 => Some("GB"), // United Kingdom of Great Britain and Northern Ireland
            236 => Some("GI"), // Gibraltar
            237 => Some("GR"), // Greece
            238 => Some("HR"), // Croatia
            239 => Some("GR"), // Greece
            240 => Some("GR"), // Greece
            241 => Some("GR"), // Greece
            242 => Some("MA"), // Morocco
            243 => Some("HU"), // Hungary
            244 => Some("NL"), // Netherlands
            245 => Some("NL"), // Netherlands
            246 => Some("NL"), // Netherlands
            247 => Some("IT"), // Italy
            248 => Some("MT"), // Malta
            249 => Some("MT"), // Malta
            250 => Some("IE"), // Ireland
            251 => Some("IS"), // Iceland
            252 => Some("LI"), // Liechtenstein
            253 => Some("LU"), // Luxembourg
            254 => Some("MC"), // Monaco
            255 => Some("PT"), // Portugal
            256 => Some("MT"), // Malta
            257 => Some("NO"), // Norway
            258 => Some("NO"), // Norway
            259 => Some("NO"), // Norway
            261 => Some("PL"), // Poland
            262 => Some("ME"), // Montenegro
            263 => Some("PT"), // Portugal
            264 => Some("RO"), // Romania
            265 => Some("SE"), // Sweden
            266 => Some("SE"), // Sweden
            267 => Some("SK"), // Slovakia
            268 => Some("SM"), // San Marino
            269 => Some("CH"), // Switzerland
            270 => Some("CZ"), // Czechia
            271 => Some("TR"), // Turkey
            272 => Some("UA"), // Ukraine
            273 => Some("RU"), // Russian Federation
            274 => Some("MK"), // Republic of North Macedonia
            275 => Some("LV"), // Latvia
            276 => Some("EE"), // Estonia
            277 => Some("LT"), // Lithuania
            278 => Some("SI"), // Slovenia
            279 => Some("RS"), // Serbia
            301 => Some("AI"), // Anguilla
            303 => Some("US"), // United States of America
            304 => Some("AG"), // Antigua and Barbuda
            305 => Some("AG"), // Antigua and Barbuda
            306 => Some("BQ"), // Bonaire, Sint Eustatius and Saba
//            306 => Some("CW"), // Curaçao
//            306 => Some("SX"), // Sint Maarten
            307 => Some("AW"), // Aruba
            308 => Some("BS"), // Bahamas
            309 => Some("BS"), // Bahamas
            310 => Some("BM"), // Bermuda
            311 => Some("BS"), // Bahamas
            312 => Some("BZ"), // Belize
            314 => Some("BB"), // Barbados
            316 => Some("CA"), // Canada
            319 => Some("KY"), // Cayman Islands
            321 => Some("CR"), // Costa Rica
            323 => Some("CU"), // Cuba
            325 => Some("DM"), // Dominica
            327 => Some("DO"), // Dominican Republic
            329 => Some("GP"), // Guadeloupe
            330 => Some("GD"), // Grenada
            331 => Some("GL"), // Greenland
            332 => Some("GT"), // Guatemala
            334 => Some("HN"), // Honduras
            336 => Some("HT"), // Haiti
            338 => Some("US"), // United States of America
            339 => Some("JM"), // Jamaica
            341 => Some("KN"), // Saint Kitts and Nevis
            343 => Some("LC"), // Saint Lucia
            345 => Some("MX"), // Mexico
            347 => Some("MQ"), // Martinique
            348 => Some("MS"), // Montserrat
            350 => Some("NI"), // Nicaragua
            351 => Some("PA"), // Panama
            352 => Some("PA"), // Panama
            353 => Some("PA"), // Panama
            354 => Some("PA"), // Panama
            355 => Some("PA"), // Panama
            356 => Some("PA"), // Panama
            357 => Some("PA"), // Panama
            358 => Some("PR"), // Puerto Rico
            359 => Some("SV"), // El Salvador
            361 => Some("PM"), // Saint Pierre and Miquelon
            362 => Some("TT"), // Trinidad and Tobago
            364 => Some("TC"), // Turks and Caicos Islands
            366 => Some("US"), // United States of America
            367 => Some("US"), // United States of America
            368 => Some("US"), // United States of America
            369 => Some("US"), // United States of America
            370 => Some("PA"), // Panama
            371 => Some("PA"), // Panama
            372 => Some("PA"), // Panama
            373 => Some("PA"), // Panama
            374 => Some("PA"), // Panama
            375 => Some("VC"), // Saint Vincent and the Grenadines
            376 => Some("VC"), // Saint Vincent and the Grenadines
            377 => Some("VC"), // Saint Vincent and the Grenadines
            378 => Some("VG"), // British Virgin Islands
            379 => Some("VI"), // United States Virgin Islands
            401 => Some("AF"), // Afghanistan
            403 => Some("SA"), // Saudi Arabia
            405 => Some("BD"), // Bangladesh
            408 => Some("BH"), // Bahrain
            410 => Some("BT"), // Bhutan
            412 => Some("CN"), // China
            413 => Some("CN"), // China
            414 => Some("CN"), // China
            416 => Some("TW"), // Taiwan
            417 => Some("LK"), // Sri Lanka
            419 => Some("IN"), // India
            422 => Some("IR"), // Iran
            423 => Some("AZ"), // Azerbaijan
            425 => Some("IQ"), // Iraq
            428 => Some("IL"), // Israel
            431 => Some("JP"), // Japan
            432 => Some("JP"), // Japan
            434 => Some("TM"), // Turkmenistan
            436 => Some("KZ"), // Kazakhstan
            437 => Some("UZ"), // Uzbekistan
            438 => Some("JO"), // Jordan
            440 => Some("KR"), // Korea
            441 => Some("KR"), // Korea
            443 => Some("PS"), // Palestine, State of
            445 => Some("KR"), // Korea
            447 => Some("KW"), // Kuwait
            450 => Some("LB"), // Lebanon
            451 => Some("KG"), // Kyrgyzstan
            453 => Some("MO"), // Macao
            455 => Some("MV"), // Maldives
            457 => Some("MN"), // Mongolia
            459 => Some("NP"), // Nepal
            461 => Some("OM"), // Oman
            463 => Some("PK"), // Pakistan
            466 => Some("QA"), // Qatar
            468 => Some("SY"), // Syrian Arab Republic
            470 => Some("AE"), // United Arab Emirates
            471 => Some("AE"), // United Arab Emirates
            472 => Some("TJ"), // Tajikistan
            473 => Some("YE"), // Yemen
            475 => Some("YE"), // Yemen
            477 => Some("HK"), // Hong Kong
            478 => Some("BA"), // Bosnia and Herzegovina
            501 => Some("TF"), // French Southern Territories
            503 => Some("AU"), // Australia
            506 => Some("MM"), // Myanmar
            508 => Some("BN"), // Brunei Darussalam
            510 => Some("FM"), // Micronesia
            511 => Some("PW"), // Palau
            512 => Some("NZ"), // New Zealand
            514 => Some("KH"), // Cambodia
            515 => Some("KH"), // Cambodia
            516 => Some("CX"), // Christmas Island
            518 => Some("CK"), // Cook Islands
            520 => Some("FJ"), // Fiji
            523 => Some("CC"), // Cocos Islands
            525 => Some("ID"), // Indonesia
            529 => Some("KI"), // Kiribati
            531 => Some("LA"), // Lao People's Democratic Republic
            533 => Some("MY"), // Malaysia
            536 => Some("MP"), // Northern Mariana Islands
            538 => Some("MH"), // Marshall Islands
            540 => Some("NC"), // New Caledonia
            542 => Some("NU"), // Niue
            544 => Some("NR"), // Nauru
            546 => Some("PF"), // French Polynesia
            548 => Some("PH"), // Philippines
            550 => Some("TL"), // Timor-Leste
            553 => Some("PG"), // Papua New Guinea
            555 => Some("PN"), // Pitcairn
            557 => Some("SB"), // Solomon Islands
            559 => Some("AS"), // American Samoa
            561 => Some("WS"), // Samoa
            563 => Some("SG"), // Singapore
            564 => Some("SG"), // Singapore
            565 => Some("SG"), // Singapore
            566 => Some("SG"), // Singapore
            567 => Some("TH"), // Thailand
            570 => Some("TO"), // Tonga
            572 => Some("TV"), // Tuvalu
            574 => Some("VN"), // Viet Nam
            576 => Some("VU"), // Vanuatu
            577 => Some("VU"), // Vanuatu
            578 => Some("WF"), // Wallis and Futuna
            601 => Some("ZA"), // South Africa
            603 => Some("AO"), // Angola
            605 => Some("DZ"), // Algeria
            607 => Some("TF"), // French Southern Territories
            608 => Some("SH"), // Saint Helena, Ascension and Tristan da Cunha
            609 => Some("BI"), // Burundi
            610 => Some("BJ"), // Benin
            611 => Some("BW"), // Botswana
            612 => Some("CF"), // Central African Republic
            613 => Some("CM"), // Cameroon
            615 => Some("CG"), // Congo
            616 => Some("KM"), // Comoros
            617 => Some("CV"), // Cabo Verde
            618 => Some("TF"), // French Southern Territories
            619 => Some("CI"), // Côte d'Ivoire
            620 => Some("KM"), // Comoros
            621 => Some("DJ"), // Djibouti
            622 => Some("EG"), // Egypt
            624 => Some("ET"), // Ethiopia
            625 => Some("ER"), // Eritrea
            626 => Some("GA"), // Gabon
            627 => Some("GH"), // Ghana
            629 => Some("GM"), // Gambia
            630 => Some("GW"), // Guinea-Bissau
            631 => Some("GQ"), // Equatorial Guinea
            632 => Some("GN"), // Guinea
            633 => Some("BF"), // Burkina Faso
            634 => Some("KE"), // Kenya
            635 => Some("TF"), // French Southern Territories
            636 => Some("LR"), // Liberia
            637 => Some("LR"), // Liberia
            638 => Some("SS"), // South Sudan
            642 => Some("LY"), // Libya
            644 => Some("LS"), // Lesotho
            645 => Some("MU"), // Mauritius
            647 => Some("MG"), // Madagascar
            649 => Some("ML"), // Mali
            650 => Some("MZ"), // Mozambique
            654 => Some("MR"), // Mauritania
            655 => Some("MW"), // Malawi
            656 => Some("NE"), // Niger
            657 => Some("NG"), // Nigeria
            659 => Some("NA"), // Namibia
            660 => Some("TF"), // French Southern Territories
            661 => Some("RW"), // Rwanda
            662 => Some("SD"), // Sudan
            663 => Some("SN"), // Senegal
            664 => Some("SC"), // Seychelles
            665 => Some("SH"), // Saint Helena, Ascension and Tristan da Cunha
            666 => Some("SO"), // Somalia
            667 => Some("SL"), // Sierra Leone
            668 => Some("ST"), // Sao Tome and Principe
            669 => Some("SZ"), // Eswatini
            670 => Some("TD"), // Chad
            671 => Some("TG"), // Togo
            672 => Some("TN"), // Tunisia
            674 => Some("TZ"), // Tanzania, United Republic of
            675 => Some("UG"), // Uganda
            676 => Some("CG"), // Congo
            677 => Some("TZ"), // Tanzania, United Republic of
            678 => Some("ZM"), // Zambia
            679 => Some("ZW"), // Zimbabwe
            701 => Some("AR"), // Argentina
            710 => Some("BR"), // Brazil
            720 => Some("BO"), // Bolivia
            725 => Some("CL"), // Chile
            730 => Some("CO"), // Colombia
            735 => Some("EC"), // Ecuador
            740 => Some("FK"), // Falkland Islands [Malvinas]
            745 => Some("GF"), // French Guiana
            750 => Some("GY"), // Guyana
            755 => Some("PY"), // Paraguay
            760 => Some("PE"), // Peru
            765 => Some("SR"), // Suriname
            770 => Some("UY"), // Uruguay
            775 => Some("VE"), // Venezuela
            _ => { None }
        }
    }
}

// -------------------------------------------------------------------------------------------------
/// GGA - Time, position, and fix related data
#[derive(Clone, Debug, PartialEq)]
pub struct PositionTimeSatelites {
    /// Navigation system
    pub system: NavigationSystem,

    /// UTC of position fix
    pub timestamp: Option<DateTime<Utc>>,
    
    /// Latitude in degrees
    pub latitude: Option<f64>,

    /// Longitude in degrees
    pub longitude: Option<f64>,
    
    /// GPS QUality indicator
    pub quality: GpsQualityIndicator,
    
    /// Number of satellites in use
    pub satellite_count: Option<u8>,
    
    /// Horizontal dilution of position
    pub hdop: Option<f64>,
    
    /// Altitude above mean sea level (metres)
    pub altitude: Option<f64>,
    
    /// Height of geoid (mean sea level) above WGS84 ellipsoid
    pub geoid_separation: Option<f64>,
    
    /// Age of differential GPS data record, Type 1 or Type 9.
    pub age_of_dgps: Option<f64>,
    
    /// Reference station ID, range 0000-4095
    pub ref_station_id: Option<u16>,
}

/// Part of GGA.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GpsQualityIndicator {
    Invalid, // 0
    GpsFix, // 1
    DGpsFix, // 2
    PpsFix, // 3
    RealTimeKinematic, // 4
    RealTimeKinematicFloat, // 5
    DeadReckoning, // 6
    ManualInputMode, // 7
    SimulationMode, // 8
}

impl GpsQualityIndicator {
    pub fn new(a: u8) -> GpsQualityIndicator {
        match a {
            0 => GpsQualityIndicator::Invalid,
            1 => GpsQualityIndicator::GpsFix,
            2 => GpsQualityIndicator::DGpsFix,
            3 => GpsQualityIndicator::PpsFix,
            4 => GpsQualityIndicator::RealTimeKinematic,
            5 => GpsQualityIndicator::RealTimeKinematicFloat,
            6 => GpsQualityIndicator::DeadReckoning,
            7 => GpsQualityIndicator::ManualInputMode,
            8 => GpsQualityIndicator::SimulationMode,
            _ => GpsQualityIndicator::Invalid,
        }
    }
}

// -------------------------------------------------------------------------------------------------
/// RMC - Position, velocity, and time (Recommended Minimum sentence C)
#[derive(Clone, Debug, PartialEq)]
pub struct PositionVelocityTime {
    /// Navigation system
    pub system: NavigationSystem,

    /// Fix datetime based on HHMMSS and DDMMYY
    pub timestamp: Option<DateTime<Utc>>,
    
    /// Status: true = active, false = void.
    pub status_active: Option<bool>,
    
    /// Latitude in degrees    
    pub latitude: Option<f64>,

    /// Longitude in degrees    
    pub longitude: Option<f64>,
    
    /// Speed over ground in knots
    pub speed_knots: Option<f64>,
    
    /// Track angle in degrees (True)
    pub bearing: Option<f64>,
    
    /// Magnetic variation in degrees
    pub variation: Option<f64>
}

// -------------------------------------------------------------------------------------------------
/// GSA - GPS DOP and active satellites
#[derive(Clone, Debug, PartialEq)]
pub struct PositionPrecision {
    /// Navigation system
    pub system: NavigationSystem,

    /// Mode 1: true = automatic, false = manual
    pub mode1_automatic: Option<bool>,
    
    /// Mode 2, fix type: 
    pub mode2_3d: Option<FixMode>,
    
    /// PRN numbers used (space for 12)
    pub prn_numbers: Vec<u8>,
    
    /// Position (3D) dilution of precision
    pub pdop: Option<f64>,
    
    /// Horizontal dilution of precision
    pub hdop: Option<f64>,
    
    /// Vertical dilution of precision
    pub vdop: Option<f64>,
}

/// Position fix type.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FixMode {
    /// No fix.
    NotAvailable,
    
    /// 2D fix.
    Fix2D,
    
    /// 3d fix.
    Fix3D,
}

// -------------------------------------------------------------------------------------------------
/// GSV - Satellite information (for GSV).
#[derive(Clone, Debug, PartialEq)]
pub struct SatelliteInformation {
    /// Navigation system
    pub system: NavigationSystem,

    /// Satellite PRN number
    pub prn_number: u8,
    
    /// Elevation in degrees (max 90°)
    pub elevation: Option<u8>,
    
    /// Azimuth in degrees from True north (0°-359°)
    pub azimuth: Option<u16>,
    
    /// SNR, 0-99 dB, None when not tracking
    pub snr: Option<u8>,
}

// -------------------------------------------------------------------------------------------------

/// VTG - Track made good and speed over ground
#[derive(Clone, Debug, PartialEq)]
pub struct VelocityMadeGood {
    /// Navigation system
    pub system: NavigationSystem,

    /// Course over ground (CoG), degrees True
    pub cog_true: Option<f64>,
    
    /// Course over ground (CoG), degrees Magnetic
    pub cog_magnetic: Option<f64>,
    
    /// Speed over ground (SoG), knots
    pub sog_knots: Option<f64>,
    
    /// Speed over ground (SoG), km/h
    pub sog_kph: Option<f64>,
    
    /// FAA mode indicator
    pub faa_mode: Option<FaaMode>,
}

/// NMEA 2.3 standard has this information.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FaaMode {
    /// Autonomous mode (automatic 2D/3D)
    Autonomous,
    
    /// Differential GPS mode (DGPS).
    Differential,
    
    /// Estimated (dead-reckoning) data.
    Estimated,
    
    /// No valid data available.
    NotValid,
    
    /// Simulated data.
    Simulator,
}

impl FaaMode {
    pub fn new(val: &str) -> Result<FaaMode, String> {
        match val {
            "A" => Ok(FaaMode::Autonomous),
            "D" => Ok(FaaMode::Differential),
            "E" => Ok(FaaMode::Estimated),
            "N" => Ok(FaaMode::NotValid),
            _ => { Err(format!("Unrecognized FAA information value: {}", val)) }
        }
    }

    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            FaaMode::Autonomous => { write!(f, "A") }
            FaaMode::Differential => { write!(f, "D") }
            FaaMode::Estimated => { write!(f, "E") }
            FaaMode::NotValid => { write!(f, "N") }
            _ => { write!(f, "?") }
        }
        
    }
}

// -------------------------------------------------------------------------------------------------

/// GLL - Geographic Position - Latitude/Longitude
#[derive(Clone, Debug, PartialEq)]
pub struct Position {
    /// Navigation system
    pub system: NavigationSystem,

    /// Latitude in degrees.
    pub latitude: Option<f64>,

    /// Longitude in degrees.
    pub longitude: Option<f64>,

    /// UTC of position fix
    pub timestamp: Option<DateTime<Utc>>,

    /// True = data valid, false = data invalid.
    pub data_valid: Option<bool>,
    
    /// FAA mode indicator (NMEA 2.3 and later).
    pub faa_mode: Option<FaaMode>,
}

// -------------------------------------------------------------------------------------------------

/// Used to store partial sentences between function calls.
pub struct NmeaStore {
    saved_fragments: HashMap<String, String>,
    saved_vsds: HashMap<u32, VesselStaticData>,
}

impl NmeaStore {
    /// Default constructor.
    pub fn new() -> NmeaStore {
        NmeaStore {
            saved_fragments: HashMap::new(),
            saved_vsds:      HashMap::new(),
        }
    }
    
    /// Push string-to-string mapping to store.
    pub fn push_string(&mut self, key: String, value: String) {
        self.saved_fragments.insert(key, value);
    }

    /// Pull string-to-string mapping by key from store.
    pub fn pull_string(&mut self, key: String) -> Option<String> {
        self.saved_fragments.remove(&key)
    }

    /// Tests whether the given string-to-string mapping exists in the store.
    pub fn contains_key(&mut self, key: String) -> bool {
        self.saved_fragments.contains_key(&key)
    }

    /// Return number of string-to-string mappings stored.
    pub fn strings_count(&self) -> usize {
        self.saved_fragments.len()
    }

    /// Push MMSI-to-VesselStaticData mapping to store.
    pub fn push_vsd(&mut self, mmsi: u32, vsd: VesselStaticData) {
        self.saved_vsds.insert(mmsi, vsd);
    }
    
    /// Pull MMSI-to-VesselStaticData mapping from store.
    pub fn pull_vsd(&mut self, mmsi: u32) -> Option<VesselStaticData> {
        self.saved_vsds.remove(&mmsi)
    }

    /// Return number of MMSI-to-VesselStaticData mappings in store.    
    pub fn vsds_count(&self) -> usize {
        self.saved_vsds.len()
    }
}

// -------------------------------------------------------------------------------------------------

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_nmea_store() {
        let mut store = NmeaStore::new();
        
        // String test
        store.push_string("a".into(), "b".into());
        assert_eq!(store.strings_count(), 1);
        store.push_string("c".into(), "d".into());
        assert_eq!(store.strings_count(), 2);
        store.pull_string("a".into());
        assert_eq!(store.strings_count(), 1);
        store.pull_string("c".into());
        assert_eq!(store.strings_count(), 0);
        
        // VesselStaticData test
        store.push_vsd(1, Default::default());
        assert_eq!(store.vsds_count(), 1);
        store.push_vsd(2, Default::default());
        assert_eq!(store.vsds_count(), 2);
        store.pull_vsd(1);
        assert_eq!(store.vsds_count(), 1);
        store.pull_vsd(2);
        assert_eq!(store.vsds_count(), 0);
    }

    #[test]
    fn test_mmsi_to_country_code_conversion() {
        let mut vsd = VesselStaticData::default();
        
        vsd.mmsi = 230992580; assert_eq!(vsd.country().unwrap(), "FI");
        vsd.mmsi = 276009860; assert_eq!(vsd.country().unwrap(), "EE");
        vsd.mmsi = 265803690; assert_eq!(vsd.country().unwrap(), "SE");
        vsd.mmsi = 273353180; assert_eq!(vsd.country().unwrap(), "RU");
        vsd.mmsi = 211805060; assert_eq!(vsd.country().unwrap(), "DE");
        vsd.mmsi = 257037270; assert_eq!(vsd.country().unwrap(), "NO");
        vsd.mmsi = 227232370; assert_eq!(vsd.country().unwrap(), "FR");
        vsd.mmsi = 248221000; assert_eq!(vsd.country().unwrap(), "MT");
        vsd.mmsi = 374190000; assert_eq!(vsd.country().unwrap(), "PA");
        vsd.mmsi = 412511368; assert_eq!(vsd.country().unwrap(), "CN");
        vsd.mmsi = 512003200; assert_eq!(vsd.country().unwrap(), "NZ");
        vsd.mmsi = 995126020; assert_eq!(vsd.country(), None);
        vsd.mmsi = 2300049; assert_eq!(vsd.country(), None);
    }

}