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

export let dialogueMessageQueryManipulator: ResponseManipulatorHandler = (
  cache,
  cacheKey,
  request
) => {
  const cacheData: any[] = cache.getCacheData(cacheKey);
  if (cacheData) {
    let pivotIndex = -1;
    const count = request.variables.count ?? 36;
    if (request.variables.pivot) {
      for (let i = 0; i < cacheData.length; i++) {
        if (cacheData[i].id === request.variables.pivot) {
          pivotIndex = i + 1; // pivotIndex-th message is already in chat
          break;
        }
      }
    } else {
      pivotIndex = 0;
      return cacheData.slice(pivotIndex, pivotIndex + count);
    }
    if (pivotIndex !== -1) {
      return cacheData.slice(pivotIndex, pivotIndex + count);
    }
  }

  return undefined;
};
