hrdf-parser 0.9.4

This library is dedicated to the parsing of the HRDF format. For the moment, it can only parse the Swiss version of the HRDF format.
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
use std::path::Path;

/// # List of track and bus platform information.
///
/// ## File contains:
///
/// The first part defines validities, TUs and journeys, which are associated with the track infrastructure in the second part:
/// * HS no.
/// * Journey number
/// * Transport company code
/// * Track link ID “#…”
/// * Service running times;
/// * Days of operation
///
/// ## Example (excerpt):
///
/// `
/// ...
/// 8500010 000003 000011 #0000001      053751 % HS-Nr. 8500010, Fahrt-Nr. 3, TU-Code 11 (SBB), Link #1, keine Verkehrszeit, Verkehrstage-bit: 053751 (s. BITFELD-Datei)
/// 8500010 000003 000011 #0000002      053056 % ...
/// 8500010 000003 000011 #0000003      097398 % ...
/// 8500010 000003 000011 #0000001      001345 % HS-Nr. 8500010, Fahrt-Nr. 3, TU-Code 11 (SBB), Link #1, keine Verkehrszeit, Verkehrstage-bit: 001345 (!) anders als erste Zeile!
/// ...
/// 8014413 005338 8006C5 #0000001      075277 % ...
/// 8014331 005338 8006C5 #0000003 0025 049496 % HS-Nr. 8014331, Fahrt-Nr. 5338, TU-Code 8006C5 (DB Regio), Link #3, Verkehrszeit 00:25, Verkehrstage-bit: 049496 (s. BITFELD-Datei)
/// 8014281 005339 8006C5 #0000002      080554 % ...
/// ...
/// `
///
/// The second part describes the infrastructure (tracks or bus platforms) of the stop:
/// * HS no.
/// * Track link ID “#…” linked with part 1 in combination with HS no.
/// * G = track, A = section, T = separator
///
/// ## Description
///
/// `
/// ...
/// 8500010 #0000004 G '9'  % HS-Nr. 8500010, Link #4, Gleis "9"
/// 8500010 #0000001 G '11' % HS-Nr. 8500010, Link #4, Gleis "11" -> Übereinstimmung mit Erster und vierter Zeile im Beispiel oben!, d.h. die beiden mit unterschiedlichen Gültigkeiten beziehen sich auf Gleis 11
/// 8500010 #0000003 G '12' % ...
/// ...
/// 8014330 #0000001 G '2'  % ...
/// 8014331 #0000001 G '1'  % ...
/// 8014331 #0000002 G '2'  % ...
/// 8014331 #0000003 G '3'  % HS-Nr. 8014331, Link #3, Gleis "3" -> Übereinstimmung mit zweiter Zeile im Zweiten Abschnitt im Beispiel oben!
/// 8014332 #0000002 G '1'  % ...
/// ...
/// `
///
/// This creates the overall picture by linking the two pieces of information.
///
/// IMPORTANT NOTE on *WGS and *LV95, as well as “GLEIS” vs “GLEISE”: These two files will replace the “pure” GLEIS and GLEIS_* files in Switzerland in 2024. So GLEISE_WGS and GLEISE_LV95 remain. Accordingly, we have also documented these directly here.
///
/// With the replacement, only the second part changes as follows (further details on this topic and the implementation in Switzerland can be found in the RV):
///
/// * HS no.
/// * Track link ID “#…” linked with part 1 in combination with HS no.
/// * Changed: Track = G, A = Section, g A = Swiss Location ID (SLOID), k = Coordinates (longitude, latitude, altitude)
/// * Important: contrary to the standard, track and section data are in different lines and not in one!
///
/// ## Description
/// * ‘ ‘ means no explicit designation at the location
///
/// ## Example (excerpt):
///
/// `
/// ...
/// 8500207 #0000001 G '1'                    % Hs-Nr. 8500207, Link #1, Gleis "1"
/// 8500207 #0000001 A 'AB'                   % Hs-Nr. 8500207, Link #1, Gleis-Abschnitt "AB" <-> Die verlinkte Fahrt hält an Gleis 1, Abschnitt AB (Tripel HS-Nr., Link, Bezeichnungen)
/// 8503000 #0000002 G '13'                   % ...
/// 8574200 #0000003 G ''                     % Hs-Nr. 8574200, Link #3, Gleis "" <-> Gleis hat keine explizite Bezeichnung am Ort
/// 8574200 #0000003 g A ch:1:sloid:74200:1:3 % Hs-Nr. 8574200, Link #3, SLOID "ch:1:sloid:74200:1:3" <-> Gleis "" hat SLOID wie beschrieben
/// 8574200 #0000003 k 2692827 1247287 680    % Hs-Nr. 8574200, Link #3, Koordinaten 269.. 124.. Höhe 680 <-> Gleis "" mit SLOID hat Koordinaten wie beschrieben
/// ...
/// `
///
///
/// 3 file(s).
/// File(s) read by the parser:
/// GLEIS, GLEIS_LV95, GLEIS_WGS
/// ---
/// Note: this parser collects both the Platform and JourneyPlatform resources.
use nom::{
    IResult, Parser,
    branch::alt,
    bytes::{complete::tag, streaming::take_until},
    character::{
        char,
        complete::{multispace0, multispace1, space1},
    },
    combinator::{map, opt},
    number::complete::double,
    sequence::{delimited, preceded},
};
use rustc_hash::{FxHashMap, FxHashSet};

use crate::{
    JourneyId, Version,
    error::{HResult, HrdfError},
    models::{CoordinateSystem, Coordinates, JourneyPlatform, Model, Platform},
    parsing::{
        error::{PResult, ParsingError},
        helpers::{
            i32_from_n_digits_parser, optional_i32_from_n_digits_parser, read_lines,
            string_from_n_chars_parser, string_till_eol_parser,
        },
    },
    storage::ResourceStorage,
    utils::{AutoIncrement, create_time_from_value},
};

enum PlatformLine {
    JourneyPlatform {
        stop_id: i32,
        journey_id: i32,
        administration: String,
        index: i32,
        time: Option<i32>,
        bit_field_id: Option<i32>,
    },
    Platform {
        stop_id: i32,
        index: i32,
        platform_name: String,
        code: Option<String>,
    },
    // Currently unused. Maybe we will want to use it at some point
    Section {
        #[allow(unused)]
        stop_id: i32,
        #[allow(unused)]
        index: i32,
        #[allow(unused)]
        section_data: String,
    },
    Sloid {
        stop_id: i32,
        index: i32,
        sloid: String,
    },
    Coord {
        stop_id: i32,
        index: i32,
        x: f64,
        y: f64,
        #[allow(unused)]
        altitude: Option<f64>,
    },
}

fn journey_platform_combinator(input: &str) -> IResult<&str, PlatformLine> {
    map(
        (
            i32_from_n_digits_parser(7),
            preceded(char(' '), i32_from_n_digits_parser(6)),
            preceded(char(' '), string_from_n_chars_parser(6)),
            preceded((space1, tag("#")), i32_from_n_digits_parser(7)),
            preceded(char(' '), optional_i32_from_n_digits_parser(4)),
            preceded(char(' '), optional_i32_from_n_digits_parser(6)),
        ),
        |(stop_id, journey_id, administration, index, time, bit_field_id)| {
            PlatformLine::JourneyPlatform {
                stop_id,
                journey_id,
                administration,
                index,
                time,
                bit_field_id,
            }
        },
    )
    .parse(input)
}

fn platform_combinator(input: &str) -> IResult<&str, PlatformLine> {
    map(
        (
            i32_from_n_digits_parser(7),
            preceded(tag(" #"), i32_from_n_digits_parser(7)),
            preceded(tag(" G "), delimited(tag("'"), take_until("'"), tag("'"))),
            preceded(
                opt(tag(" A ")),
                opt(delimited(tag("'"), take_until("'"), tag("'"))),
            ),
        ),
        |(stop_id, index, platform_name, code)| PlatformLine::Platform {
            stop_id,
            index,
            platform_name: platform_name.to_string(),
            code: code.map(String::from),
        },
    )
    .parse(input)
}

fn section_combinator(input: &str) -> IResult<&str, PlatformLine> {
    map(
        (
            i32_from_n_digits_parser(7),
            preceded(tag(" #"), i32_from_n_digits_parser(7)),
            preceded(tag(" A "), string_till_eol_parser),
        ),
        |(stop_id, index, section_data)| PlatformLine::Section {
            stop_id,
            index,
            section_data,
        },
    )
    .parse(input)
}

fn coord_combinator(input: &str) -> IResult<&str, PlatformLine> {
    map(
        (
            i32_from_n_digits_parser(7),
            preceded(tag(" #"), i32_from_n_digits_parser(7)),
            preceded(
                alt((tag(" k"), tag(" K"))),
                (
                    preceded(multispace0, double),
                    preceded(multispace1, double),
                    opt(preceded(multispace1, double)),
                ),
            ),
        ),
        |(stop_id, index, (x, y, altitude))| PlatformLine::Coord {
            stop_id,
            index,
            x,
            y,
            altitude,
        },
    )
    .parse(input)
}

fn sloid_combinator(input: &str) -> IResult<&str, PlatformLine> {
    map(
        (
            i32_from_n_digits_parser(7),
            preceded(tag(" #"), i32_from_n_digits_parser(7)),
            alt((
                preceded(tag(" g A "), string_till_eol_parser),
                preceded(tag(" I A "), string_till_eol_parser),
            )),
        ),
        |(stop_id, index, sloid)| PlatformLine::Sloid {
            stop_id,
            index,
            sloid,
        },
    )
    .parse(input)
}

fn parse_line(
    line: &str,
    platforms: &mut FxHashMap<i32, Platform>,
    journey_platform: &mut FxHashMap<(i32, i32), JourneyPlatform>,
    platforms_pk_type_converter: &mut FxHashMap<(i32, i32), i32>,
    journeys_pk_type_converter: &FxHashSet<JourneyId>,
    auto_increment: &AutoIncrement,
    coordinate_system: CoordinateSystem,
) -> PResult<()> {
    let (_, platform_row) = alt((
        journey_platform_combinator,
        platform_combinator,
        section_combinator,
        sloid_combinator,
        coord_combinator,
    ))
    .parse(line)?;

    match platform_row {
        PlatformLine::JourneyPlatform {
            stop_id,
            journey_id,
            administration,
            index,
            time,
            bit_field_id,
        } => {
            let key = (journey_id, administration.clone());
            let _journey_id = journeys_pk_type_converter.get(&key).ok_or_else(|| {
                ParsingError::UnknownId(format!(
                    "Journey Legacy Id (journey_id, administration): ({journey_id}, {administration})"
                ))
            })?;

            if !platforms_pk_type_converter.is_empty() {
                let platform_id = *platforms_pk_type_converter
                    .get(&(stop_id, index))
                    .ok_or_else(|| {
                        ParsingError::UnknownId(format!(
                            "Legacy Platform Id (stop_id, index): ({stop_id}, {index})"
                        ))
                    })?;

                let time = time.map(|x| create_time_from_value(x as u32)).transpose()?;

                let jp_instance = JourneyPlatform::new(
                    journey_id,
                    administration,
                    platform_id,
                    time,
                    bit_field_id,
                );
                journey_platform.insert(jp_instance.id(), jp_instance);
            }
        }
        PlatformLine::Section {
            stop_id: _,
            index: _,
            section_data: _,
        } => {
            // TODO: We should maybe use this data at some point
        }
        PlatformLine::Platform {
            stop_id,
            index,
            platform_name,
            code,
        } => {
            let id = auto_increment.next();

            let id = platforms_pk_type_converter
                .entry((stop_id, index))
                .or_insert(id);

            // if let Some(previous) = platforms_pk_type_converter.insert((stop_id, index), id) {
            //     log::warn!(
            //         "Warning: previous id {previous} for ({stop_id}, {index}). The pair (stop_id, index), ({stop_id}, {index}), is not unique."
            //     );
            // };
            platforms
                .entry(*id)
                .or_insert(Platform::new(*id, platform_name, code, stop_id));
        }
        PlatformLine::Sloid {
            stop_id,
            index,
            sloid,
        } => {
            let id = platforms_pk_type_converter
                .get(&(stop_id, index))
                .ok_or_else(|| {
                    ParsingError::UnknownId(format!(
                        "Legacy Platform Id (stop_id, index): ({stop_id}, {index})"
                    ))
                })?;

            platforms
                .get_mut(id)
                .ok_or_else(|| ParsingError::UnknownId(format!("Unknown platforms Id: {id}")))?
                .set_sloid(sloid);
            // TODO: We should maybe check for consistency between LV95 and GWS sloids
        }
        PlatformLine::Coord {
            stop_id,
            index,
            x,
            y,
            altitude: _,
        } => {
            let id = platforms_pk_type_converter
                .get(&(stop_id, index))
                .ok_or_else(|| {
                    ParsingError::UnknownId(format!(
                        "Legacy Platform Id (stop_id, index): ({stop_id}, {index})"
                    ))
                })?;

            let platform = platforms
                .get_mut(id)
                .ok_or_else(|| ParsingError::UnknownId(format!("Unknown platforms Id: {id}")))?;

            match coordinate_system {
                c @ CoordinateSystem::LV95 => {
                    let value = Coordinates::new(c, x, y);
                    platform.set_lv95_coordinates(value);
                }
                c @ CoordinateSystem::WGS84 => {
                    // WGS84 coordinates are stored in reverse order for some unknown reason.
                    let value = Coordinates::new(c, y, x);
                    platform.set_wgs84_coordinates(value);
                }
            }
        }
    }
    Ok(())
}

pub fn parse(
    version: Version,
    path: &Path,
    journeys_pk_type_converter: &FxHashSet<JourneyId>,
) -> HResult<(ResourceStorage<JourneyPlatform>, ResourceStorage<Platform>)> {
    let prefix = match version {
        Version::V_5_40_41_2_0_7 => Ok("GLEISE"),
        Version::V_5_40_41_2_0_4 | Version::V_5_40_41_2_0_5 | Version::V_5_40_41_2_0_6 => {
            Ok("GLEIS")
        }
        _ => Err(HrdfError::SupportedVersion(version)),
    }?;
    let auto_increment = AutoIncrement::new();
    let mut platforms = FxHashMap::default();
    let mut platforms_pk_type_converter = FxHashMap::default();

    let mut journey_platform = FxHashMap::default();

    log::info!("Parsing {prefix}_LV95...");
    let file = path.join(format!("{prefix}_LV95"));
    let platforms_lv95 = read_lines(&file, 0)?;
    platforms_lv95
        .into_iter()
        .enumerate()
        .filter(|(_, line)| !line.trim().is_empty())
        .try_for_each(|(line_number, line)| {
            parse_line(
                &line,
                &mut platforms,
                &mut journey_platform,
                &mut platforms_pk_type_converter,
                journeys_pk_type_converter,
                &auto_increment,
                CoordinateSystem::LV95,
            )
            .map_err(|e| HrdfError::Parsing {
                error: e,
                file: String::from(file.to_string_lossy()),
                line,
                line_number,
            })
        })?;

    log::info!("Parsing {prefix}_WGS...");
    let file = path.join(format!("{prefix}_WGS"));
    let platforms_wgs84 = read_lines(&file, 0)?;
    platforms_wgs84
        .into_iter()
        .enumerate()
        .filter(|(_, line)| !line.trim().is_empty())
        .try_for_each(|(line_number, line)| {
            parse_line(
                &line,
                &mut platforms,
                &mut journey_platform,
                &mut platforms_pk_type_converter,
                journeys_pk_type_converter,
                &auto_increment,
                CoordinateSystem::WGS84,
            )
            .map_err(|e| HrdfError::Parsing {
                error: e,
                file: String::from(file.to_string_lossy()),
                line,
                line_number,
            })
        })?;

    Ok((
        ResourceStorage::new(journey_platform),
        ResourceStorage::new(platforms),
    ))
}
#[cfg(test)]
mod tests {
    use crate::parsing::tests::get_json_values;

    use super::*;
    use pretty_assertions::assert_eq;

    #[test]
    fn test_journey_platform_combinator_basic() {
        let input = "8500010 000003 000011 #0000001      053751";
        let result = journey_platform_combinator(input);
        assert!(result.is_ok());
        let (_, platform_line) = result.unwrap();
        match platform_line {
            PlatformLine::JourneyPlatform {
                stop_id,
                journey_id,
                administration,
                index,
                time,
                bit_field_id,
            } => {
                assert_eq!(stop_id, 8500010);
                assert_eq!(journey_id, 3);
                assert_eq!(administration, "000011");
                assert_eq!(index, 1);
                assert_eq!(time, None);
                assert_eq!(bit_field_id, Some(53751));
            }
            _ => panic!("Expected JourneyPlatform variant"),
        }
    }

    #[test]
    fn test_journey_platform_combinator_with_time() {
        let input = "8014331 005338 8006C5 #0000003 0025 049496";
        let result = journey_platform_combinator(input);
        assert!(result.is_ok());
        let (_, platform_line) = result.unwrap();
        match platform_line {
            PlatformLine::JourneyPlatform {
                stop_id,
                journey_id,
                administration,
                index,
                time,
                bit_field_id,
            } => {
                assert_eq!(stop_id, 8014331);
                assert_eq!(journey_id, 5338);
                assert_eq!(administration, "8006C5");
                assert_eq!(index, 3);
                assert_eq!(time, Some(25));
                assert_eq!(bit_field_id, Some(49496));
            }
            _ => panic!("Expected JourneyPlatform variant"),
        }
    }

    #[test]
    fn test_journey_platform_combinator_spaces_for_optional_fields() {
        let input = "8500010 000003 000011 #0000002      000000";
        let result = journey_platform_combinator(input);
        assert!(result.is_ok());
        let (_, platform_line) = result.unwrap();
        match platform_line {
            PlatformLine::JourneyPlatform {
                stop_id,
                journey_id,
                administration,
                index,
                time,
                bit_field_id,
            } => {
                assert_eq!(stop_id, 8500010);
                assert_eq!(journey_id, 3);
                assert_eq!(administration, "000011");
                assert_eq!(index, 2);
                assert_eq!(time, None);
                // bitfield_id of 0 is valid (means journey operates every day)
                assert_eq!(bit_field_id, Some(0));
            }
            _ => panic!("Expected JourneyPlatform variant"),
        }
    }

    #[test]
    fn test_platform_combinator_basic() {
        let input = "8500010 #0000004 G '9'";
        let result = platform_combinator(input);
        assert!(result.is_ok());
        let (_, platform_line) = result.unwrap();
        match platform_line {
            PlatformLine::Platform {
                stop_id,
                index,
                platform_name,
                code,
            } => {
                assert_eq!(stop_id, 8500010);
                assert_eq!(index, 4);
                assert_eq!(platform_name, "9");
                assert_eq!(code, None);
            }
            _ => panic!("Expected Platform variant"),
        }
    }

    #[test]
    fn test_platform_combinator_double_digit() {
        let input = "8500010 #0000001 G '11'";
        let result = platform_combinator(input);
        assert!(result.is_ok());
        let (_, platform_line) = result.unwrap();
        match platform_line {
            PlatformLine::Platform {
                stop_id,
                index,
                platform_name,
                code,
            } => {
                assert_eq!(stop_id, 8500010);
                assert_eq!(index, 1);
                assert_eq!(platform_name, "11");
                assert_eq!(code, None);
            }
            _ => panic!("Expected Platform variant"),
        }
    }

    #[test]
    fn test_platform_combinator_with_section() {
        let input = "8500207 #0000001 G '1' A 'AB'";
        let result = platform_combinator(input);
        assert!(result.is_ok());
        let (_, platform_line) = result.unwrap();
        match platform_line {
            PlatformLine::Platform {
                stop_id,
                index,
                platform_name,
                code,
            } => {
                assert_eq!(stop_id, 8500207);
                assert_eq!(index, 1);
                assert_eq!(platform_name, "1");
                assert_eq!(code, Some("AB".to_string()));
            }
            _ => panic!("Expected Platform variant"),
        }
    }

    #[test]
    fn test_platform_combinator_empty_name() {
        let input = "8574200 #0000003 G ''";
        let result = platform_combinator(input);
        assert!(result.is_ok());
        let (_, platform_line) = result.unwrap();
        match platform_line {
            PlatformLine::Platform {
                stop_id,
                index,
                platform_name,
                code,
            } => {
                assert_eq!(stop_id, 8574200);
                assert_eq!(index, 3);
                assert_eq!(platform_name, "");
                assert_eq!(code, None);
            }
            _ => panic!("Expected Platform variant"),
        }
    }

    #[test]
    fn test_section_combinator() {
        let input = "8500207 #0000001 A 'AB'";
        let result = section_combinator(input);
        assert!(result.is_ok());
        let (_, platform_line) = result.unwrap();
        match platform_line {
            PlatformLine::Section {
                stop_id,
                index,
                section_data,
            } => {
                assert_eq!(stop_id, 8500207);
                assert_eq!(index, 1);
                assert_eq!(section_data, "'AB'");
            }
            _ => panic!("Expected Section variant"),
        }
    }

    #[test]
    fn test_sloid_combinator_lowercase() {
        let input = "8574200 #0000003 g A ch:1:sloid:74200:1:3";
        let result = sloid_combinator(input);
        assert!(result.is_ok());
        let (_, platform_line) = result.unwrap();
        match platform_line {
            PlatformLine::Sloid {
                stop_id,
                index,
                sloid,
            } => {
                assert_eq!(stop_id, 8574200);
                assert_eq!(index, 3);
                assert_eq!(sloid, "ch:1:sloid:74200:1:3");
            }
            _ => panic!("Expected Sloid variant"),
        }
    }

    #[test]
    fn test_sloid_combinator_uppercase() {
        let input = "8574200 #0000003 I A ch:1:sloid:74200:1:3";
        let result = sloid_combinator(input);
        assert!(result.is_ok());
        let (_, platform_line) = result.unwrap();
        match platform_line {
            PlatformLine::Sloid {
                stop_id,
                index,
                sloid,
            } => {
                assert_eq!(stop_id, 8574200);
                assert_eq!(index, 3);
                assert_eq!(sloid, "ch:1:sloid:74200:1:3");
            }
            _ => panic!("Expected Sloid variant"),
        }
    }

    #[test]
    fn test_coord_combinator_with_altitude() {
        let input = "8574200 #0000003 k 2692827 1247287 680";
        let result = coord_combinator(input);
        assert!(result.is_ok());
        let (_, platform_line) = result.unwrap();
        match platform_line {
            PlatformLine::Coord {
                stop_id,
                index,
                x,
                y,
                altitude,
            } => {
                assert_eq!(stop_id, 8574200);
                assert_eq!(index, 3);
                assert_eq!(x, 2692827.0);
                assert_eq!(y, 1247287.0);
                assert_eq!(altitude, Some(680.0));
            }
            _ => panic!("Expected Coord variant"),
        }
    }

    #[test]
    fn test_coord_combinator_without_altitude() {
        let input = "8574200 #0000003 k 2692827.5 1247287.2";
        let result = coord_combinator(input);
        assert!(result.is_ok());
        let (_, platform_line) = result.unwrap();
        match platform_line {
            PlatformLine::Coord {
                stop_id,
                index,
                x,
                y,
                altitude,
            } => {
                assert_eq!(stop_id, 8574200);
                assert_eq!(index, 3);
                assert_eq!(x, 2692827.5);
                assert_eq!(y, 1247287.2);
                assert_eq!(altitude, None);
            }
            _ => panic!("Expected Coord variant"),
        }
    }

    #[test]
    fn test_coord_combinator_uppercase_k() {
        let input = "8574200 #0000003 K 2692827 1247287 680";
        let result = coord_combinator(input);
        assert!(result.is_ok());
        let (_, platform_line) = result.unwrap();
        match platform_line {
            PlatformLine::Coord {
                stop_id,
                index,
                x,
                y,
                altitude,
            } => {
                assert_eq!(stop_id, 8574200);
                assert_eq!(index, 3);
                assert_eq!(x, 2692827.0);
                assert_eq!(y, 1247287.0);
                assert_eq!(altitude, Some(680.0));
            }
            _ => panic!("Expected Coord variant"),
        }
    }

    #[test]
    fn test_parse_line_platform_creation() {
        let mut platforms = FxHashMap::default();
        let mut journey_platform = FxHashMap::default();
        let mut platforms_pk_type_converter = FxHashMap::default();
        let journeys_pk_type_converter = FxHashSet::default();
        let auto_increment = AutoIncrement::new();

        parse_line(
            "8500010 #0000001 G '11'",
            &mut platforms,
            &mut journey_platform,
            &mut platforms_pk_type_converter,
            &journeys_pk_type_converter,
            &auto_increment,
            CoordinateSystem::LV95,
        )
        .unwrap();
        assert_eq!(platforms.len(), 1);
        assert_eq!(platforms_pk_type_converter.len(), 1);
        let platform = platforms.get(&1).unwrap();
        println!("{}", serde_json::to_string(&platform).unwrap());
        let reference = r#"
            {
                "id":1,
                "name":"11",
                "sectors":null,
                "stop_id":8500010,
                "sloid":"",
                "lv95_coordinates":{"coordinate_system":"LV95","x":0.0,"y":0.0},
                "wgs84_coordinates":{"coordinate_system":"LV95","x":0.0,"y":0.0}
            }"#;
        let (platform, reference) = get_json_values(platform, reference).unwrap();
        assert_eq!(platform, reference);
    }

    #[test]
    #[should_panic]
    fn test_parse_line_sloid_requires_existing_platform() {
        let mut platforms = FxHashMap::default();
        let mut journey_platform = FxHashMap::default();
        let mut platforms_pk_type_converter = FxHashMap::default();
        let journeys_pk_type_converter = FxHashSet::default();
        let auto_increment = AutoIncrement::new();

        parse_line(
            "8574200 #0000003 g A ch:1:sloid:74200:1:3",
            &mut platforms,
            &mut journey_platform,
            &mut platforms_pk_type_converter,
            &journeys_pk_type_converter,
            &auto_increment,
            CoordinateSystem::LV95,
        )
        .unwrap();
    }

    #[test]
    #[should_panic]
    fn test_parse_line_coord_requires_existing_platform() {
        let mut platforms = FxHashMap::default();
        let mut journey_platform = FxHashMap::default();
        let mut platforms_pk_type_converter = FxHashMap::default();
        let journeys_pk_type_converter = FxHashSet::default();
        let auto_increment = AutoIncrement::new();

        parse_line(
            "8574200 #0000003 k 2692827 1247287 680",
            &mut platforms,
            &mut journey_platform,
            &mut platforms_pk_type_converter,
            &journeys_pk_type_converter,
            &auto_increment,
            CoordinateSystem::LV95,
        )
        .unwrap();
    }

    #[test]
    fn test_parse_line_complete_platform_sequence() {
        let mut platforms = FxHashMap::default();
        let mut journey_platform = FxHashMap::default();
        let mut platforms_pk_type_converter = FxHashMap::default();
        let journeys_pk_type_converter = FxHashSet::default();
        let auto_increment = AutoIncrement::new();

        // Create platform
        parse_line(
            "8574200 #0000003 G '5'",
            &mut platforms,
            &mut journey_platform,
            &mut platforms_pk_type_converter,
            &journeys_pk_type_converter,
            &auto_increment,
            CoordinateSystem::LV95,
        )
        .unwrap();

        // Add SLOID
        parse_line(
            "8574200 #0000003 g A ch:1:sloid:74200:1:3",
            &mut platforms,
            &mut journey_platform,
            &mut platforms_pk_type_converter,
            &journeys_pk_type_converter,
            &auto_increment,
            CoordinateSystem::LV95,
        )
        .unwrap();

        // Add coordinates
        parse_line(
            "8574200 #0000003 k 2692827 1247287 680",
            &mut platforms,
            &mut journey_platform,
            &mut platforms_pk_type_converter,
            &journeys_pk_type_converter,
            &auto_increment,
            CoordinateSystem::LV95,
        )
        .unwrap();

        assert_eq!(platforms.len(), 1);
        let platform_id = *platforms_pk_type_converter.get(&(8574200, 3)).unwrap();
        assert_eq!(platform_id, 1);
        let platform = platforms.get(&platform_id).unwrap();
        assert_eq!(platform.id(), platform_id);

        println!("{}", serde_json::to_string(&platform).unwrap());
        let reference = r#"
            {
                "id":1,
                "name":"5",
                "sectors":null,
                "stop_id":8574200,
                "sloid":"ch:1:sloid:74200:1:3",
                "lv95_coordinates":{"coordinate_system":"LV95","x":2692827.0,"y":1247287.0},
                "wgs84_coordinates":{"coordinate_system":"LV95","x":0.0,"y":0.0}
            }"#;
        let (platform, reference) = get_json_values(platform, reference).unwrap();
        assert_eq!(platform, reference);
    }

    #[test]
    fn test_coordinate_system_wgs84_reverses_coordinates() {
        let mut platforms = FxHashMap::default();
        let mut journey_platform = FxHashMap::default();
        let mut platforms_pk_type_converter = FxHashMap::default();
        let journeys_pk_type_converter = FxHashSet::default();
        let auto_increment = AutoIncrement::new();

        // Create platform
        parse_line(
            "8500010 #0000001 G '1'",
            &mut platforms,
            &mut journey_platform,
            &mut platforms_pk_type_converter,
            &journeys_pk_type_converter,
            &auto_increment,
            CoordinateSystem::WGS84,
        )
        .unwrap();

        // Add WGS84 coordinates (should be reversed)
        parse_line(
            "8500010 #0000001 k 47.123 8.456",
            &mut platforms,
            &mut journey_platform,
            &mut platforms_pk_type_converter,
            &journeys_pk_type_converter,
            &AutoIncrement::new(),
            CoordinateSystem::WGS84,
        )
        .unwrap();

        // The test verifies that WGS84 coordinates are parsed and stored correctly
        // Note: WGS84 coordinates are reversed (y, x instead of x, y) in the implementation
        // at line 368 in platform_parser.rs
    }

    #[test]
    #[should_panic]
    fn test_journey_platform_requires_valid_journey() {
        let mut platforms = FxHashMap::default();
        let mut journey_platform = FxHashMap::default();
        let mut platforms_pk_type_converter = FxHashMap::default();
        let journeys_pk_type_converter = FxHashSet::default(); // Empty set
        let auto_increment = AutoIncrement::new();

        parse_line(
            "8500010 000003 000011 #0000001      053751",
            &mut platforms,
            &mut journey_platform,
            &mut platforms_pk_type_converter,
            &journeys_pk_type_converter,
            &auto_increment,
            CoordinateSystem::LV95,
        )
        .unwrap();
    }
}