import 'package:guru_app/financial/product/product_model.dart';

/// Created by Haoyi on 6/1/21

class ProductStore<T extends Product> {
  final Map<ProductId, T> data = <ProductId, T>{};

  ProductStore();

  void putProduct(T item) {
    data[item.productId] = item;
  }

  void putAllProducts(List<T> items) {
    for (var item in items) {
      putProduct(item);
    }
  }

  List<T> getProducts(List<ProductId> ids) {
    final result = <T>[];
    for (var id in ids) {
      final item = getProduct(id);
      if (item != null) {
        result.add(item);
      }
    }
    return result;
  }

  T? getProduct(ProductId productId) {
    return productId.isValid() ? data[productId] : null;
  }

  bool existsProduct(ProductId productId) {
    return productId.isValid() == true && data.containsKey(productId);
  }

  bool existsProducts(List<ProductId> productIds) {
    for (var productId in productIds) {
      if (existsProduct(productId)) {
        return true;
      }
    }
    return false;
  }

  T? getFirstProduct(List<ProductId> productIds) {
    for (var productId in productIds) {
      final product = getProduct(productId);
      if (product != null) {
        return product;
      }
    }
    return null;
  }

  // Map<IapType, List<String>> filterUncertaintyProductIds(List<ProductId> productIds) {
  //   final uncertaintyIds = <IapType, List<String>>{};
  //
  //   for (ProductId productId in productIds) {
  //     final id = productId.platformProductId;
  //     if (!data.containsKey(id)) {
  //       IapType iapType = IapType.Product;
  //       if (PurchaseUtils.isSubscriptionProductId(id)) {
  //         iapType = IapType.Subscription;
  //       }
  //       List<String> ids = uncertaintyIds[iapType];
  //       if (ids == null) {
  //         ids = <String>[];
  //         uncertaintyIds[iapType] = ids;
  //       }
  //       ids.add(id);
  //     }
  //   }
  //   return uncertaintyIds;
  // }

  ProductStore<T> clone() {
    return ProductStore()..data.addAll(data);
  }
}
