import 'package:http/http.dart' as http; import 'dart:convert'; import '../model/flood_station.dart'; import '../model/reading.dart'; import 'date_utility.dart'; class Api { Api._(); static const String _rootUrl = 'https://environment.data.gov.uk/flood-monitoring'; /// Fetches all stationszt static Future> fetchAllStations() async { List stations = []; final response = await http.get(Uri.parse('$_rootUrl/id/stations')); if (response.statusCode == 200) { final Map jsonStr = jsonDecode(response.body); for (final str in jsonStr['items']) { stations.add(FloodStation.fromMap(str)); } } return stations; } /// Fetches all stations whose label contain [label] static Future> fetchFilteredStations(String label) async { List stations = []; final response = await http.get(Uri.parse('$_rootUrl/id/stations?search=$label')); if (response.statusCode == 200) { final Map jsonStr = jsonDecode(response.body); for (final str in jsonStr['items']) { stations.add(FloodStation.fromMap(str)); } } return stations; } /// [limit] limits the number of entries that are requested from the API and [offset] returns the /// list starting from the specified number static Future> fetchStationsByRange( int limit, int offset) async { List stations = []; final response = await http .get(Uri.parse('$_rootUrl/id/stations?_limit=$limit&_offset=$offset')); if (response.statusCode == 200) { final Map jsonStr = jsonDecode(response.body); for (final str in jsonStr['items']) { stations.add(FloodStation.fromMap(str)); } } return stations; } /// Fetches all readings from the station with the specified [stationId] from the last 24h static Future> fetchReadingsFromStation( String stationId) async { List readings = []; final dateTime = DateUtility.currentUKTimeUtc.subtract(Duration(days: 1)).toUtc(); final url = '$_rootUrl/id/stations/$stationId/readings?since=${dateTime.toIso8601String()}&_sorted'; final response = await http.get(Uri.parse(url)); if (response.statusCode == 200) { final Map jsonStr = jsonDecode(response.body); for (final str in jsonStr['items']) { readings.add(Reading.fromMap(str)); } } return readings.reversed.toList(); } }