import "dart:io";

import "utils.dart";
import "stops_bc.dart";

typedef InOutTrips = (TripID, TripID);

class BcRoutesParser extends Parser<Route> {
  final routesFile = File(bcDataDir / "routes.txt");
  final tripsFile = File(bcDataDir / "trips.txt");

  final stopParser = BcStopParser();

  Future<Map<RouteID, Route>> getRoutes() async => {
    for (final csv in await readCsv(routesFile))
      RouteID.fromBcCsv(csv): Route.fromBcCsv(csv),
  };

  Future<Map<RouteID, TripID>> getTripForRoutes(Map<TripID, List<StopID>> trips) async {
    final tripsForRoutes = <RouteID, List<TripID>>{};
    for (final row in await readCsv(tripsFile)) {
      final routeID = RouteID(Provider.bc, row[0]);
      final trip = TripID(row[2]);
      // print(trip);
      tripsForRoutes.addToList(routeID, trip);
    }
    return {
      for (final (routeID, tripsForRoute) in tripsForRoutes.records)
        routeID: tripsForRoute.max((trip) => trips[trip]!.length),
    };
  }

  @override
  Future<Iterable<Route>> parse() async {
    final routes = await getRoutes();
    final trips = await stopParser.getTrips();
    final tripsForRoutes = await getTripForRoutes(trips);

    for (final (routeID, route) in routes.records) {
      final longestTrip = tripsForRoutes[routeID]!;
      final stops = trips[longestTrip]!;
      route.stops.addAll(stops);
    }
    return routes.values;
  }
}
