import "dart:convert";

import "package:http/http.dart" as http;

import "package:client/data.dart";

import "service.dart";

class ApiService extends Service {
  final client = http.Client();

  @override
  Future<void> init() async { }

  Uri get _base => Uri(scheme: "https", host: "localhost", port: 5000);

  Future<List<T>?> _getAll<T>(Uri uri, FromJson<T> fromJson) async {
    try {
      final response = await client.get(uri);
      if (response.statusCode != 200) return null;
      final json = jsonDecode(response.body) as List;
      return [
        for (final obj in json.cast<Json>())
          fromJson(obj),
      ];
    } catch (error) {
      return null;
    }
  }

  Future<List<Trip>?> getTrips() => _getAll(
    _base.replace(path: "/trips"),
    Trip.fromJson,
  );

  Future<Path?> getPath({
    required Coordinates start,
    required Coordinates end,
  }) => _getAll(
    _base.replace(
      path: "/path",
    ).replace(
      queryParameters: {
        "start_lat": start.lat.toString(),
        "start_lon": start.long.toString(),
        "end_lat": end.lat.toString(),
        "end_lon": end.long.toString(),
        "time": DateTime.now().millisecondsSinceEpoch.toString(),
      },
    ),
    PathStep.fromJson,
  );
}
