import 'package:hl_lieferservice/model/delivery.dart';
import 'package:intl/intl.dart';
import 'package:json_annotation/json_annotation.dart';

part 'delivery_update.g.dart';

@JsonSerializable(fieldRename: FieldRename.snake)
class DeliveryOptionUpdateDTO {
  DeliveryOptionUpdateDTO({
    required this.numerical,
    required this.value,
    required this.key,
  });

  bool numerical;
  String value;
  String key;

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

  Map<dynamic, dynamic> toJson() => _$DeliveryOptionUpdateDTOToJson(this);

  factory DeliveryOptionUpdateDTO.fromEntity(DeliveryOption option) {
    return DeliveryOptionUpdateDTO(
      numerical: option.numerical,
      value: option.value,
      key: option.key,
    );
  }
}

@JsonSerializable(fieldRename: FieldRename.snake)
class DeliveryUpdateDTO {
  DeliveryUpdateDTO({
    required this.deliveryId,
    this.finishedDate,
    this.selectedPaymentMethodId,
    this.options,
    this.state,
    this.carId,
  });

  String deliveryId;
  String? finishedDate;
  String? state;
  String? carId;
  String? selectedPaymentMethodId;
  List<DeliveryOptionUpdateDTO>? options;

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

  factory DeliveryUpdateDTO.fromEntity(Delivery delivery) {
    String state = "";

    switch (delivery.state) {
      case DeliveryState.finished:
        state = "geliefert";
        break;
      case DeliveryState.ongoing:
        state = "laufend";
        break;
      case DeliveryState.onhold:
        state = "vertagt";
        break;
      case DeliveryState.canceled:
        state = "abgebrochen";
        break;
    }

    return DeliveryUpdateDTO(
      deliveryId: delivery.id,
      state: state,
      carId: delivery.carId?.toString() ,
      selectedPaymentMethodId: delivery.payment.id,
      options: delivery.options.map(DeliveryOptionUpdateDTO.fromEntity).toList(),
      finishedDate: delivery.state == DeliveryState.finished
          ? DateFormat('yyyy-MM-dd HH:mm').format(DateTime.now())
          : null,
    );
  }

  Map<dynamic, dynamic> toJson() => _$DeliveryUpdateDTOToJson(this);
}
