

import 'dart:typed_data';

import 'package:bus_infotainment/audio_cache.dart';
import 'package:bus_infotainment/utils/NameBeautify.dart';
import 'package:csv/csv.dart';

class BusSequences {

  Map<String, BusRoute> routes = {};

  BusSequences.fromCSV(String csv) {

    List<List<dynamic>> rowsAsListOfValues = const CsvToListConverter().convert(csv);

    rowsAsListOfValues.removeAt(0);

    for (int i = 0; i < rowsAsListOfValues.length; i++) {

      try {

        List<dynamic> entries = rowsAsListOfValues[i];

        String routeNumber = entries[0].toString();

        BusRoute route = routes.containsKey(routeNumber) ? routes[routeNumber]! : BusRoute(routeNumber: routeNumber);

        int routeVariant = entries[1];

        BusRouteVariant variant = route.routeVariants.containsKey(routeVariant) ? route.routeVariants[routeVariant]! : BusRouteVariant(routeVariant: routeVariant, busRoute: route);

        BusRouteStops stop = BusRouteStops();

        stop.stopName = entries[6].toString();
        stop.stopCode = entries[4].toString();
        stop.easting = entries[7];
        stop.northing = entries[8];

        variant.busStops.add(stop);

        route.routeVariants[routeVariant] = variant;
        routes[routeNumber] = route;

      } catch (e) {
        // print("Error parsing bus sequence: $e");
      }

    }
  }

}

class BusRoute {

  String routeNumber = "";

  AnnouncementCache? announcementCache;

  Map<int, BusRouteVariant> routeVariants = {};

  BusRoute({
    this.routeNumber = "-1",
    this.announcementCache,
  });

}

class BusRouteVariant {

    int routeVariant = -1;

    List<BusRouteStops> busStops = [];

    late BusRoute busRoute;

    BusRouteVariant({
      this.routeVariant = -1,
      required this.busRoute,
    });
}

class BusRouteStops {

  String stopName = "";

  int easting = -1;
  int northing = -1;

  String stopCode = "";

  String get formattedStopName {
    return NameBeautify.beautifyStopName(stopName);
  }

  String getAudioFileName() {

    // Convert the stop name to all caps
    String stopName = this.stopName.toUpperCase();

    stopName = NameBeautify.beautifyStopName(stopName);

    // replace & with N
    stopName = stopName.replaceAll('&', 'N');

    stopName = stopName.replaceAll('/', '');

    stopName = stopName.replaceAll('\'', '');

    stopName = stopName.replaceAll('  ', ' ');

    // Replace space with underscore
    stopName = stopName.replaceAll(' ', '_');

    // convert to all caps
    stopName = stopName.toUpperCase();

    stopName = "S_${stopName}_001.mp3";

    return stopName;


  }

}