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<List<FloodStation>> fetchAllStations() async {
    List<FloodStation> stations = [];
    final response = await http.get(Uri.parse('$_rootUrl/id/stations'));
    if (response.statusCode == 200) {
      final Map<String, dynamic> 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<List<FloodStation>> fetchFilteredStations(String label) async {
    List<FloodStation> stations = [];
    final response =
        await http.get(Uri.parse('$_rootUrl/id/stations?search=$label'));
    if (response.statusCode == 200) {
      final Map<String, dynamic> 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<List<FloodStation>> fetchStationsByRange(
      int limit, int offset) async {
    List<FloodStation> stations = [];
    final response = await http
        .get(Uri.parse('$_rootUrl/id/stations?_limit=$limit&_offset=$offset'));
    if (response.statusCode == 200) {
      final Map<String, dynamic> 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<List<Reading>> fetchReadingsFromStation(
      String stationId) async {
    List<Reading> 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<String, dynamic> jsonStr = jsonDecode(response.body);
      for (final str in jsonStr['items']) {
        readings.add(Reading.fromMap(str));
      }
    }
    return readings.reversed.toList();
  }
}
