import "package:flutter/foundation.dart" show debugPrint, kDebugMode;

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

import "api_client.dart";
import "service.dart";

class ApiService extends Service {
  static const usingDocker = !kDebugMode;
  final _client = ApiClient();

  @override
  Future<void> init() async {
    debugPrint("Running with Docker? $usingDocker");
  }

  Uri get _base => usingDocker
    ? Uri(path: "api/")
    : Uri(scheme: "http", host: "localhost", port: 80);

  Future<List<Trip>?> getTrips() => _client.getJsonList(
    _base.resolve("trips"),
    Trip.fromJson,
    key: "path",
  );

  Future<Path?> getPath({
    required Coordinates start,
    required Coordinates end,
  }) => _client.getJsonList(
    _base.resolve("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(),
      },
    ),
    key: "path",
    PathStep.fromJson,
  );

  Future<String?> getPath2({
    required Coordinates start,
    required Coordinates end,
  }) async {
    final uri = Uri.parse("/tmp-api/path").replace(
      queryParameters: {
        "start_lat": start.lat.toString(),
        "start_lon": start.long.toString(),
        "end_lat": end.lat.toString(),
        "end_lon": end.long.toString(),
      },
    );
    try {
      final response = await http.get(uri);
      return response.body;
    // Any error should show null
    // ignore: avoid_catches_without_on_clauses
    } catch (error) {
      return null;
    }
  }

  Future<List<Stop>?> getStops() => _client.getJsonList(
    _base.resolve("stops"),
    Stop.fromJson,
  );
}
