using System.Globalization; using System.Text.RegularExpressions; using Schaad.OpenData.Traffic.Models; namespace Schaad.OpenData.Traffic.Source; public static partial class ThurgauTrafficMapper { public static TrafficImport Map(IEnumerable records) { var counts = new List(); var firstRecords = new Dictionary(); var directions = new Dictionary>(); foreach (var record in records) { if (record.Coordinates is null || !TryParseDate(record.Date, out var date) || record.Hour is < 0 or > 23) { continue; } firstRecords.TryAdd(record.Code, record); if (!directions.TryGetValue(record.Code, out var stationDirections)) { stationDirections = new Dictionary(StringComparer.Ordinal); directions[record.Code] = stationDirections; } var direction = Clean(record.Direction); if (!stationDirections.TryGetValue(direction, out var pooled)) { pooled = direction; stationDirections[direction] = pooled; } counts.Add(new HourlyCount(record.Code, pooled, date, record.Hour, ToCounts(record))); } var stations = firstRecords.Values .Select(r => new Station( r.Code, Clean(r.Name), Clean(r.Municipality), Clean(r.Address), Clean(r.Road), new GeoPoint(r.Coordinates!.Lat, r.Coordinates.Lon), [.. directions[r.Code].Keys.Order(StringComparer.Ordinal)])) .OrderBy(s => s.Code) .ToList(); return new TrafficImport(stations, counts); } private static VehicleCounts ToCounts(ThurgauTrafficRecord record) => new( record.Bus ?? 0, record.Motorcycle ?? 0, record.Car ?? 0, record.CarWithTrailer ?? 0, record.Van ?? 0, record.VanWithTrailer ?? 0, record.VanWithSemiTrailer ?? 0, record.Truck ?? 0, record.TruckWithTrailer ?? 0, record.SemiTrailerTruck ?? 0); private static bool TryParseDate(string? value, out DateOnly date) { date = default; return value is { Length: >= 10 } && DateOnly.TryParseExact(value[..10], "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out date); } private static string Clean(string? value) => MultipleSpaces().Replace(value ?? "", " ").Trim(); [GeneratedRegex(@"\s+")] private static partial Regex MultipleSpaces(); }