import "utils.dart";
import "route.dart";
import "provider.dart";

extension type StopID(String id) {
  StopID.fromJson(dynamic value) : id = value.toString();
}

class Stop with Encodable {
  final StopID id;
  final String name;
  final String? description;
  final Coordinates coordinates;
  final Provider provider;
  final Set<String> routes;
  final Set<RouteID> routeIDs;

  Stop({
    required this.id,
    required this.name,
    required this.description,
    required this.coordinates,
    required this.provider,
  }) : routes = {}, routeIDs = {};

  Stop.fromJson(Json json) :
    id = StopID(json["id"]),
    name = json["name"],
    description = json["description"],
    coordinates = (lat: json["latitude"], long: json["longitude"]),
    provider = Provider.fromJson(json["provider"]),
    routes = (json["routes"] as List).cast<String>().toSet(),
    routeIDs = {
      for (final routeID in (json["route_ids"] as List))
        RouteID.fromJson(routeID),
    };

  Stop.fromOcctJson(Json json) :
    id = StopID.fromJson(json["id"]),
    name = json["name"],
    description = null,
    coordinates = (lat: json["lat"], long: json["lng"]),
    provider = Provider.occt,
    routes = <String>{},
    routeIDs = <RouteID>{};

  @override
  Map<String, dynamic> toJson() => {
    "id": id.id,
    "name": name,
    "description": description,
    "latitude": coordinates.lat,
    "longitude": coordinates.long,
    "provider": provider.id,
    "routes": routes.toList(),
    "route_ids": routeIDs.toList(),
  };

  String get summary {
    final buffer = StringBuffer();
    if (description != null) {
      buffer.writeln(description);
    }
    if (routes.isNotEmpty) {
      buffer.writeln("Routes:");
      routes.forEach(buffer.writeln);
    }
    return buffer.toString();
  }

  void addRoute(RouteID id, String name) {
    routeIDs.add(id);
    routes.add(name);
  }
}
