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 DaoTransientFolksonomy daoTransientFolksonomy =
      DaoTransientFolksonomy(localDatabase);
  final DaoFolksonomy daoFolksonomy = DaoFolksonomy(localDatabase);

  String? bearerToken;
  while (true) {
    final FolksonomyOperation? operation = _getPendingOperations(
      barcode,
      daoTransientFolksonomy,
    )?.firstOrNull;

    if (operation == null) {
      return;
    }

    if (!operation.isPerformed) {
      bearerToken ??= await _getBearerToken();

      switch (operation.type) {
        case FolksonomyAction.add:
          await _serverAdd(operation.tag, bearerToken);
          break;
        case FolksonomyAction.edit:
          await _serverEdit(operation.tag, bearerToken);
          break;
        case FolksonomyAction.remove:
          await _serverDelete(operation.tag, bearerToken);
          break;
        default:
          throw Exception('Invalid operation type: ${operation.type}');
      }

      final List<FolksonomyOperation>? pendingOperations =
          _getPendingOperations(barcode, daoTransientFolksonomy);
      if (pendingOperations == null || pendingOperations.isEmpty) {
        throw Exception(
          'As we have just performed an operation, there should be at least this operation in the queue.',
        );
      }

      pendingOperations[0].isPerformed = true;
      await daoTransientFolksonomy.put(barcode, pendingOperations);
    }

    await serverRefresh(barcode, daoFolksonomy, localDatabase);

    final List<FolksonomyOperation>? pendingOperations =
        _getPendingOperations(barcode, daoTransientFolksonomy);
    if (pendingOperations == null ||
        pendingOperations.isEmpty ||
        !pendingOperations.first.isPerformed) {
      throw Exception(
        'As we have just performed an operation, there should be at least this operation, as performed, in the queue.',
      );
    }

    pendingOperations.removeAt(0);

    if (pendingOperations.isEmpty) {
      await daoTransientFolksonomy.delete(barcode);
    } else {
      await daoTransientFolksonomy.put(barcode, pendingOperations);
    }
  }
}