import "dart:convert";

import "package:client/data.dart";
import "package:flutter/foundation.dart";
import "package:http/http.dart" as http;

class ApiClient {
  final client = http.Client();

  Future<List<T>?> getJsonList<T>(Uri uri, FromJson<T> fromJson, {String? key}) async {
    try {
      final response = await client.get(uri);
      if (response.statusCode != 200) return null;
      // No key: Assume the entire body is a list
      // With key: Assume the body is a map with a list at the key
      final listOfJson = key == null
        ? (jsonDecode(response.body) as List).cast<Json>()
        : ((jsonDecode(response.body) as Json)[key] as List).cast<Json>();
      return [
        for (final json in listOfJson)
          fromJson(json),
      ];
    // Want to catch all errors for the UI
    // ignore: avoid_catches_without_on_clauses
    } catch (error, stackTrace) {
      debugPrint("Error: $error\n$stackTrace");
      return null;
    }
  }
}
