loadBanners method

Future<List<AdItem>> loadBanners(
  1. String bannerName,
  2. String bannerSize, {
  3. bool forceRefresh = false,
})

Load banners for a banner name and size ALWAYS calls the API to fetch fresh data, regardless of cache Cache is only used as fallback if API call fails bannerSize is used for cache keys and callbacks (apiValue format like "BANNER") Automatically converts to widthxheight format (like "320x50") for API calls

Implementation

Future<List<AdItem>> loadBanners(String bannerName, String bannerSize,
    {bool forceRefresh = false}) async {
  // Convert bannerSize (apiValue format) to API format (widthxheight)
  // Handle null or empty bannerSize gracefully
  if (bannerSize.isEmpty) {
    _notifyCallbacks(bannerName, bannerSize, (callback) {
      callback.onError('Invalid banner size: empty string', null);
    });
    return [];
  }
  final sizeForApi = BannerSize.toApiBannerSize(bannerSize);

  // Always call API to get fresh data - never use cache to skip API calls
  // Cache is only used as fallback if API call fails
  try {
    List<AdItem> adItems;

    if (Platform.isIOS) {
      // iOS: syncBannerDetails returns ad items directly (single call)
      adItems = await DynamicZoneChannel.syncAndFetchBannersiOS(
          sizeForApi, bannerName);
    } else {
      // Android: Two-step flow - sync to get bannerId, then update to get ad items
      // Step 1: Sync banner details to get bannerId (use apiBannerSize format for API)
      final bannerId =
          await DynamicZoneChannel.syncBannerDetails(sizeForApi, bannerName);
      if (bannerId == null || bannerId == -1) {
        _notifyCallbacks(bannerName, bannerSize, (callback) {
          callback.onError('No matching banner found', null);
        });
        return [];
      }

      // Cache banner ID
      _bannerIds[_getKey(bannerName, bannerSize)] = bannerId;

      // Step 2: Update banner to get ad items (use apiBannerSize format for API)
      adItems = await DynamicZoneChannel.updateBanner(
          bannerName, sizeForApi, bannerId);
    }

    // Always filter: count >= limit hides. Seen this session keeps showing.
    final impressionFiltered =
        await ImpressionManager.filterByImpressionLimit(adItems);

    // Filter expired items
    final validItems =
        TTLParser.filterExpired(impressionFiltered, (item) => item.ttl);

    // Sort by priority
    final sortedItems = BannerSorter.sortByPriority(validItems);

    // Update cache
    _cache.put(bannerName, bannerSize, sortedItems);

    // Notify callbacks
    _notifyCallbacks(bannerName, bannerSize, (callback) {
      callback.onAdItemsFetched(sortedItems);
    });

    return sortedItems;
  } catch (e) {
    // If API call fails, try to return cached data as fallback
    final cached = _cache.get(bannerName, bannerSize);
    if (cached != null && cached.isNotEmpty) {
      // Return cached data but still notify about the error
      _notifyCallbacks(bannerName, bannerSize, (callback) {
        callback.onError(
            'Failed to load banners from API, using cached data: $e',
            e is Exception ? e : Exception(e.toString()));
      });
      return cached;
    }
    // No cached data available, return empty and notify error
    _notifyCallbacks(bannerName, bannerSize, (callback) {
      callback.onError('Failed to load banners: $e',
          e is Exception ? e : Exception(e.toString()));
    });
    return [];
  }
}