import React from 'react'
import { RefreshControl } from 'react-native'
import { useScreenCacheController } from './useScreenCacheController'

/**
 *
 * Create a <RefreshControl/> which on pull-to-refesh refereshes the main data and refreshes all secondary data as well
 */
export const useScreenRefreshControl = (
  retry: () => void,
  refreshing: boolean
) => {
  const { addCachePath, deleteCachePath, refreshAll } =
    useScreenCacheController()

  const refreshControl = (
    <RefreshControl
      onRefresh={() => {
        //Refresh main data
        retry()
        //Refresh additional data on screen
        refreshAll()
      }}
      refreshing={refreshing}
    />
  )

  const screenCacheController = {
    addCachePath,
    deleteCachePath,
  }

  return {
    refreshControl,
    screenContext: {
      screenCacheController,
    },
  }
}
