import 'package:fcs/domain/entities/discount_by_weight.dart';

import 'cargo_type.dart';

class Rate {
  double deliveryFee;
  double freeDeliveryWeight;
  double volumetricRatio;

  double diffDiscountWeight;
  double diffWeightRate;

  List<CargoType> cargoTypes = [];
  List<CargoType> customDuties = [];
  List<DiscountByWeight> discountByWeights = [];

  DiscountByWeight getDiscountByWeight(double weight) {
    discountByWeights.sort((d1, d2) => d2.weight.compareTo(d1.weight));
    return discountByWeights.firstWhere((e) => e.weight < weight,
        orElse: () => DiscountByWeight());
  }

  CargoType get defaultCargoType =>
      cargoTypes.firstWhere((e) => e.name == "General");

  Rate(
      {this.deliveryFee = 0,
      this.freeDeliveryWeight = 0,
      this.volumetricRatio = 0,
      this.diffDiscountWeight = 0,
      this.diffWeightRate = 0});

  factory Rate.fromMap(Map<String, dynamic> map) {
    return Rate(
      deliveryFee: (map['delivery_fee'] ?? 0).toDouble(),
      freeDeliveryWeight: (map['free_delivery_weight'] ?? 0).toDouble(),
      volumetricRatio: (map['volumetric_ratio'] ?? 0).toDouble(),
      diffDiscountWeight: (map['diff_discount_weight'] ?? 0).toDouble(),
      diffWeightRate: (map['diff_weight_rate'] ?? 0).toDouble(),
    );
  }

  Map<String, dynamic> toMap() {
    return {
      "delivery_fee": deliveryFee,
      'free_delivery_weight': freeDeliveryWeight,
      'volumetric_ratio': volumetricRatio,
      'diff_discount_weight': diffDiscountWeight,
      'diff_weight_rate': diffWeightRate,
    };
  }

  bool isChangedForEdit(Rate rate) {
    return rate.freeDeliveryWeight != this.freeDeliveryWeight ||
        rate.deliveryFee != this.deliveryFee ||
        rate.volumetricRatio != this.volumetricRatio ||
        rate.diffDiscountWeight != this.diffDiscountWeight ||
        rate.diffWeightRate != this.diffWeightRate;
  }

  @override
  String toString() {
    return 'Rate{deliveryFee:$deliveryFee,freeDeliveryWeight:$freeDeliveryWeight,volumetricRatio:$volumetricRatio,diffDiscountWeight:$diffDiscountWeight,diffWeightRate:$diffWeightRate}';
  }
}
