import { useContext, useRef } from 'react'
import { mutate } from 'swr/esm'
import { UserContext } from '../contexts/UserContext'
import * as _ from 'lodash'

/**
 *
 * This hook maintains (at the screen-level) information on which cache keys need to be invalidated when the screen is refreshed
 *
 */
export const useScreenCacheController = () => {
  const user = useContext(UserContext)
  const paths = useRef<Map<symbol, string>>(new Map())
  const addCachePath = (path: string) => {
    const key = Symbol()
    paths.current.set(key, path)
    return key
  }
  const deleteCachePath = (key: symbol) => paths.current.delete(key)
  const refreshAll = () => {
    _.uniq(Array.from(paths.current.values())).forEach((path) => {
      //Invalidate SWR cache for this key
      mutate([path, user.accessToken], true)
    })
  }

  return { addCachePath, deleteCachePath, refreshAll }
}
