import 'package:json_annotation/json_annotation.dart';

import '../../utils/jsonable.dart';

part 'car_user.g.dart';

// dart run build_runner build
@JsonSerializable(explicitToJson: true)
class CarUser implements Jsonable {
  @override
  final String? id;
  final String name;
  final String email;
  final List<String> cars;
  final Set<String> archivedCars;
  final Set<String> fcmTokens;
  final DateTime? licenceExpiration;

  CarUser({
    required this.id,
    required this.name,
    required this.email,
    required this.cars,
    required this.archivedCars,
    required this.fcmTokens,
    required this.licenceExpiration,
  });

  @override
  set id(String? newId) {}

  CarUser copyWithNewCar(String newCarId) {
    cars.add(newCarId);
    return CarUser(
      id: id,
      name: name,
      email: email,
      cars: cars,
      archivedCars: archivedCars,
      fcmTokens: fcmTokens,
      licenceExpiration: licenceExpiration,
    );
  }

  CarUser copyWithArchived(String archivedCar) {
    if (cars.remove(archivedCar)) {
      // Car archiving branch
      archivedCars.add(archivedCar);
    } else {
      // Moving car to active fleet
      cars.add(archivedCar);
      archivedCars.remove(archivedCar);
    }
    return CarUser(
      id: id,
      name: name,
      email: email,
      cars: cars,
      archivedCars: archivedCars,
      fcmTokens: fcmTokens,
      licenceExpiration: licenceExpiration,
    );
  }

  CarUser copyWithLicenceDate(DateTime? date) {
    return CarUser(
      id: id,
      name: name,
      email: email,
      cars: cars,
      archivedCars: archivedCars,
      fcmTokens: fcmTokens,
      licenceExpiration: date,
    );
  }

  factory CarUser.fromJson(Map<String, dynamic> json) =>
      _$CarUserFromJson(json);

  @override
  Map<String, dynamic> toJson() => _$CarUserToJson(this);

  @override
  String toString() {
    return 'CarUser{email: $email, licenceExpiration: $licenceExpiration}';
  }
}
