88 lines
2.9 KiB
Java
88 lines
2.9 KiB
Java
package SuMoC.backend.meteo;
|
|
|
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
|
|
|
import java.time.Instant;
|
|
import java.time.LocalDateTime;
|
|
import java.time.ZoneId;
|
|
import java.util.ArrayList;
|
|
import java.util.List;
|
|
import java.util.Optional;
|
|
|
|
public record ForecastResponse(
|
|
double latitude,
|
|
double longitude,
|
|
@JsonProperty("generationtime_ms") double generationtimeMs,
|
|
@JsonProperty("utc_offset_seconds") int utcOffsetSeconds,
|
|
String timezone,
|
|
@JsonProperty("timezone_abbreviation") String timezoneAbbreviation,
|
|
double elevation,
|
|
@JsonProperty("hourly_units") HourlyUnits hourlyUnits,
|
|
Hourly hourly
|
|
) {
|
|
private static int findIndex(ForecastResponse forecast, LocalDateTime target) {
|
|
int index = -1;
|
|
for (int i = 0; i < forecast.hourly().time().size(); i++) {
|
|
LocalDateTime entry = forecast.hourly().time().get(i);
|
|
if (entry.toLocalDate().equals(target.toLocalDate()) && entry.getHour() == target.getHour()) {
|
|
index = i;
|
|
break;
|
|
}
|
|
}
|
|
if (index == -1) throw new RuntimeException("Start or end not found in list received from meteo.");
|
|
|
|
return index;
|
|
}
|
|
|
|
/**
|
|
* Gets the weather code for a specific point in time.
|
|
*
|
|
* @param dateTime the target date and time
|
|
* @return the weather code if found, empty otherwise
|
|
*/
|
|
public Optional<Integer> getWeatherCodeAt(LocalDateTime dateTime) {
|
|
if (hourly == null || hourly.time == null || hourly.weatherCode == null) {
|
|
return Optional.empty();
|
|
}
|
|
|
|
for (int i = 0; i < hourly.time.size(); i++) {
|
|
if (hourly.time.get(i).equals(dateTime)) {
|
|
return Optional.of(hourly.weatherCode.get(i));
|
|
}
|
|
}
|
|
return Optional.empty();
|
|
}
|
|
|
|
public List<WeatherCondition> getWeatherConditionsBetween(
|
|
Instant start,
|
|
Instant end
|
|
) throws Exception {
|
|
LocalDateTime startDateTime = start.atZone(ZoneId.systemDefault()).toLocalDateTime();
|
|
LocalDateTime endDateTime = end.atZone(ZoneId.systemDefault()).toLocalDateTime();
|
|
if (start.isAfter(end)) {
|
|
throw new IllegalArgumentException("Start must be before end");
|
|
}
|
|
|
|
int startIndex = findIndex(this, startDateTime);
|
|
int endIndex = findIndex(this, endDateTime);
|
|
|
|
var results = new ArrayList<WeatherCondition>();
|
|
for (int i = startIndex; i <= endIndex; i++)
|
|
results.add(WeatherCondition.from(this.hourly().weatherCode().get(i)));
|
|
return results;
|
|
|
|
}
|
|
|
|
public record HourlyUnits(
|
|
String time,
|
|
@JsonProperty("weather_code") String weatherCode
|
|
) {
|
|
}
|
|
|
|
public record Hourly(
|
|
List<LocalDateTime> time,
|
|
@JsonProperty("weather_code") List<Integer> weatherCode
|
|
) {
|
|
}
|
|
}
|