// Import types
import CheckInUIProps from '../../../types/CheckInUIProps';
import Occurrence from '../../../shared/types/Occurrence';
import SeriesInfo from '../../../shared/types/SeriesInfo';
import OccurrenceGrouperInfo from '../../../shared/types/OccurrenceGrouperInfo';

// Import helpers
import toStringMMDDYY from '../../../shared/helpers/toStringMMDDYY';

// Import constants
import TTM_PATH_PREFIX from '../../../shared/constants/TTM_PATH_PREFIX';

// Simple cache, we don't have a TTL since this is on the browser
// i.e. this is expected to be short-lived, and issues can be resolved by reloading
const seriesListCache: Map<string, SeriesInfo[]> = new Map();

/**
 * Fetch the list of series corresponding to the event.
 * @author Benedikt Arnarsson
 * @param addArgName add arg description
 * @param addArgName add arg description
 * @returns add return description
 */
const fetchSeriesList = async (opts: CheckInUIProps): Promise<SeriesInfo[]> => {
  const {
    courseId,
    ihid,
    visitServerEndpoint,
  } = opts;
  // Check cache
  const cacheKey = `${courseId}-${ihid}`;
  const cacheRes = seriesListCache.get(cacheKey);
  if (cacheRes) {
    return cacheRes;
  }

  // We know that the occurrence list returned will only have `grouperEnabled: true`
  const occurrenceList: (Occurrence & OccurrenceGrouperInfo)[] = await visitServerEndpoint({
    path: `${TTM_PATH_PREFIX}/occurrence/series-list`,
    params: {
      courseId,
      ihid,
    }
  });

  // TODO: sort by date
  const seriesInfoList: SeriesInfo[] = occurrenceList.map((occ) => {
    const { seriesId } = occ;
    const mmddyy = toStringMMDDYY(occ);
    return {
      seriesId,
      mmddyy,
    };
  });

  // Add result to cache
  seriesListCache.set(cacheKey, seriesInfoList);

  return seriesInfoList;
};

export default fetchSeriesList;
