import "dart:io";

import "utils.dart";

class OcctStopParser extends Parser<Stop> {
  /// Taken from: https://binghamtonupublic.etaspot.net/service.php?service=get_stops&token=TESTING
  static final stopsFile = File(occtDataDir / "stops.json");

  /// Taken from: https://binghamtonupublic.etaspot.net/service.php?service=get_routes&token=TESTING
  static final routesFile = File(occtDataDir / "routes.json");

  Future<Map<StopID, Stop>> getStops() async {
    final result = <StopID, Stop>{};
    for (final stopJson in await readJson(stopsFile)) {
      final id = StopID.fromJson(stopJson["id"]);
      result[id] ??= Stop.fromOcctJson(stopJson);
    }
    return result;
  }

  Future<Map<StopID, List<RouteID>>> getRoutes() async {
    final result = <StopID, List<RouteID>>{};
    for (final json in await readJson(stopsFile)) {
      final stopID = StopID.fromJson(json["id"]);
      final routeID = RouteID(Provider.occt, json["rid"]);
      result.addToList(stopID, routeID);
    }
    return result;
  }

  Future<Map<RouteID, String>> getRouteNames() async => {
    for (final json in await readJson(routesFile))
      RouteID(Provider.occt, json["id"]): json["name"],
  };

  @override
  Future<Iterable<Stop>> parse() async {
    final stops = await getStops();
    final routes = await getRoutes();
    final routeNames = await getRouteNames();
    final routesToSkip = <RouteID>{RouteID(Provider.occt, "11")};
    for (final (stopID, stop) in stops.records) {
      for (final routeID in routes[stopID]!) {
        if (routesToSkip.contains(routeID)) continue;
        final routeName = routeNames[routeID]!;
        stop.addRoute(routeID, routeName);
      }
    }
    return stops.values;
  }
}
