execute method

  1. @override
Future<void> execute(
  1. LocalDatabase localDatabase
)
override

Executes the background task: upload, download, update locally.

Implementation

@override
Future<void> execute(LocalDatabase localDatabase) async {
  final SearchResult searchResult =
      await SearchProductsManager.searchProducts(
        ProductQuery.getReadUser(),
        ProductSearchQueryConfiguration(
          fields: <ProductField>[ProductField.BARCODE],
          parametersList: <Parameter>[
            PageSize(size: pageSize),
            PageNumber(page: pageNumber),
            const SortBy(option: SortOption.POPULARITY),
          ],
          language: ProductQuery.getLanguage(),
          country: ProductQuery.getCountry(),
          version: ProductQuery.productQueryVersion,
          activateKnowledgePanelsSimplified: true,
        ),
        uriHelper: uriProductHelper,
        type: SearchProductsType.background,
      );
  if (searchResult.products == null || searchResult.count == null) {
    throw Exception('Cannot download top barcodes');
  }
  int newTotalSize = searchResult.count!;
  if (newTotalSize > totalSize) {
    newTotalSize = totalSize;
  }
  final Set<String> barcodes = <String>{};
  for (final Product product in searchResult.products!) {
    barcodes.add(product.barcode!);
  }
  final DaoWorkBarcode daoWorkBarcode = DaoWorkBarcode(localDatabase);
  await daoWorkBarcode.putAll(work, barcodes);
  // if we haven't downloaded a full page, it means that there's no data left.
  final bool fullPageDownloaded = barcodes.length == pageSize;
  final int soFarAfter = await daoWorkBarcode.getCount(work);
  if (soFarAfter < newTotalSize && fullPageDownloaded) {
    // we still have barcodes to download
    await addTask(
      localDatabase: localDatabase,
      work: work,
      pageSize: pageSize,
      totalSize: newTotalSize,
      soFarSize: soFarAfter,
      pageNumber: pageNumber + 1,
      productType: productType,
    );
  } else {
    // we have all the barcodes; now we need to download the products.
    await BackgroundTaskDownloadProducts.addTask(
      localDatabase: localDatabase,
      work: work,
      pageSize: pageSize,
      totalSize: soFarAfter,
      soFarSize: 0,
      downloadFlag: BackgroundTaskDownloadProducts.flagMaskExcludeKP,
      productType: productType,
    );
  }
}