import 'dart:convert'; import 'package:http/http.dart' as http; import 'package:wetter/models/daily_weather_model.dart'; class BrightSkyAPI { static Future fetchForecastOfSingleDay( DateTime d, double lat, double lon) async { String dt = "${d.year}-${d.month}-${d.day}"; final response = await http.get( Uri.parse( 'https://api.brightsky.dev/weather?lat=$lat&lon=$lon&date=$dt&tz=Europe/Berlin'), headers: {"Accept": "application/json"}); if (response.statusCode == 200) { return DailyWeatherModel.fromJson(jsonDecode(response.body)); } else { throw Exception('Failed to load weather data'); } } static Future> fetchForecastForTimeRange( DateTime from, int noOfDays, double lat, double lon) async { DateTime until = from.add(Duration(days: noOfDays)); String fromDay = "${from.year}-${from.month}-${from.day}"; String untilDay = "${until.year}-${until.month}-${until.day}"; final response = await http.get( Uri.parse( 'https://api.brightsky.dev/weather?lat=$lat&lon=$lon&date=$fromDay&last_date=$untilDay&tz=Europe/Berlin'), headers: {"Accept": "application/json"}); final Map responseAsJson = jsonDecode(response.body); if (response.statusCode == 200) { List data = splitRangeToDaily(responseAsJson); return data; } else { throw Exception('Failed to load weather data'); } } static List splitRangeToDaily(Map json) { List dataPoints = json['weather']; List response = []; Map currPoint = {"weather": []}; String currDay = dataPoints[0]['timestamp'].substring(0, 10); for (var point in dataPoints) { if (currDay != point['timestamp'].substring(0, 10)) { currDay = point['timestamp'].substring(0, 10); response.add(DailyWeatherModel.fromJson(currPoint)); currPoint = {"weather": []}; } else { currPoint['weather'].add(point); } } return response; } }