using Schaad.OpenData.Weather.Models; using Schaad.OpenData.Weather.Storage; namespace Schaad.OpenData.Weather.Analysis; public static class WeatherAnalysis { private static readonly TimeSpan CurrentTolerance = TimeSpan.FromMinutes(30); public static IReadOnlyList BuildStations(WeatherSnapshot snapshot) { var byStation = snapshot.Readings.ToLookup(r => r.StationAbbr); return snapshot.Stations .Select(station => ToView(station, byStation[station.Abbr].ToList())) .ToList(); } public static IReadOnlyList BuildHistory(WeatherSnapshot snapshot, string abbr, DateTimeOffset from) => snapshot.Readings .Where(r => r.StationAbbr == abbr && r.Time >= from) .Select(r => new WeatherHistoryPoint(r.Time, r.Temperature, r.Precipitation, r.WindSpeed, r.WindGust)) .ToList(); private static WeatherStationView ToView(WeatherStation station, IReadOnlyList readings) { var latest = readings.Count > 0 ? readings[^1] : null; var recent = latest is null ? [] : readings.Where(r => r.Time > latest.Time - CurrentTolerance).Reverse().ToList(); var lastHour = latest is null ? [] : readings.Where(r => r.Time > latest.Time.AddHours(-1)).ToList(); var lastDay = latest is null ? [] : readings.Where(r => r.Time > latest.Time.AddDays(-1)).ToList(); return new WeatherStationView( station.Abbr, station.Name, station.Canton, station.HeightMasl, station.Lat, station.Lon, latest?.Time, Current(recent, r => r.Temperature), Current(recent, r => r.Humidity), Current(recent, r => r.WindSpeed), Current(recent, r => r.WindGust), Current(recent, r => r.WindDirection), Current(recent, r => r.Pressure), Sum(lastHour, r => r.Precipitation), Sum(lastDay, r => r.Precipitation), Sum(lastDay, r => r.Sunshine), lastDay.Select(r => r.Temperature).Min(), lastDay.Select(r => r.Temperature).Max(), lastDay.Select(r => r.WindGust).Max(), readings.Count > 0 ? readings[0].Time : null); } private static double? Current(IReadOnlyList newestFirst, Func value) => newestFirst.Select(value).FirstOrDefault(v => v.HasValue); private static double? Sum(IReadOnlyList readings, Func value) { var values = readings.Select(value).Where(v => v.HasValue).ToList(); return values.Count == 0 ? null : Math.Round(values.Sum(v => v!.Value), 1); } }