import { ConditionForFetchHandler } from '../../cache-logic-interface';

export let conditionFetchForDialogueMessageQuery: ConditionForFetchHandler = function (
  cache,
  cacheKey,
  request
) {
  // querying required when
  // - there is no cache
  // - there is cache, but pivot is not in found in it
  //    or its the last element in the cached message list

  const cacheData = cache.getCacheData(cacheKey);
  if (!cacheData) {
    return true;
  }

  if (request.variables.pivot) {
    if (cacheData[cacheData.length - 1].id === request.variables.pivot) {
      // pivot is the last element of cache, query more
      return true;
    }

    for (let i = 0; i < cacheData.length; i++) {
      if (cacheData[i].id === request.variables.pivot) {
        return false;
      }
    }
    // pivot is not found in the cache, query more
    return true;
  }

  // there
  return false;
};
