import { useContext } from 'react'
import { UserContext } from '../contexts/UserContext'
import { useNetwork } from '../components/useNetwork'
import { timeRangeDates } from '../util'
import { TrackScreenResponse } from '../screens/TrackScreenResponse'
import { EventType, sendAnalyticsEvent } from '../hooks/useAnalytics'
import { ArtistContext } from '../contexts/ArtistContext'
import { TimeInterval } from '../types/TimeInterval'

export const cachedTrackScreenPaths: Set<string> = new Set()

export function useTrackScreenData(isrc: string, timeInterval: TimeInterval) {
  const user = useContext(UserContext)
  const artist = useContext(ArtistContext)
  const { startDate, endDate } = timeRangeDates(timeInterval)
  const path = `screens/artist/${artist.sonyArtistId}/track/${isrc}?startDate=${startDate}&endDate=${endDate}`
  cachedTrackScreenPaths.add(path)

  const response = useNetwork<TrackScreenResponse>(path, user, () =>
    sendAnalyticsEvent(EventType.PULL_TO_REFRESH, {
      artist_selected: artist.name,
      timeframe_selected: timeInterval,
      page: 'Track Screen',
      subject: 'user',
      verb: 'refreshed',
      object: 'track',
    })
  )

  return {
    ...response,
    startDate,
    endDate,
  }
}
