updateOxF static method

Future<void> updateOxF({
  1. required LocalDatabase localDatabase,
  2. required List<String> initialBarcodes,
  3. required int locationOSMId,
  4. required LocationOSMType locationOSMType,
})

Implementation

static Future<void> updateOxF({
  required LocalDatabase localDatabase,
  required List<String> initialBarcodes,
  required int locationOSMId,
  required LocationOSMType locationOSMType,
}) async {
  final List<String> actualBarcodes = <String>[];
  for (final String barcode in initialBarcodes) {
    if (barcode.isNotEmpty) {
      actualBarcodes.add(barcode);
    }
  }
  if (actualBarcodes.isEmpty) {
    return;
  }

  final MaybeError<Location> maybeLocation =
      await OpenPricesAPIClient.getOSMLocation(
        locationOSMId: locationOSMId,
        locationOSMType: locationOSMType,
        uriHelper: ProductQuery.uriPricesHelper,
      );
  if (maybeLocation.isError) {
    return;
  }
  final Location location = maybeLocation.value;

  final List<PriceToOxF> priceToOxFList = <PriceToOxF>[
    PriceToOxF._store(location),
    PriceToOxF._country(location),
  ];
  bool atLeastOne = false;
  for (final PriceToOxF priceToOxF in priceToOxFList) {
    if (priceToOxF._isOk()) {
      atLeastOne = true;
      break;
    }
  }
  if (!atLeastOne) {
    return;
  }

  final List<String>? refreshedBarcodes;
  if (actualBarcodes.length == 1) {
    // better data from single product search
    final String barcode = actualBarcodes.first;
    final FetchedProduct fetchedProduct = await ProductRefresher()
        .silentFetchAndRefresh(
          localDatabase: localDatabase,
          barcode: barcode,
        );
    if (fetchedProduct.status != FetchedProductStatus.ok) {
      return;
    }
    refreshedBarcodes = <String>[barcode];
  } else {
    refreshedBarcodes = await ProductRefresher().silentFetchAndRefreshList(
      barcodes: actualBarcodes,
      localDatabase: localDatabase,
      productType: ProductType.food,
    );
    if (refreshedBarcodes == null || refreshedBarcodes.isEmpty) {
      return;
    }
  }

  final Map<String, Product> products = await DaoProduct(
    localDatabase,
  ).getAll(refreshedBarcodes);

  for (final Product product in products.values) {
    for (final PriceToOxF priceToOxF in priceToOxFList) {
      await priceToOxF._addTaskIfChanged(
        product: product,
        localDatabase: localDatabase,
      );
    }
  }
}