import { useContext } from 'react'
import _ from 'lodash'
import { UserContext } from '../contexts/UserContext'
import { useNetwork } from '../components/useNetwork'
import { timeRangeDates } from '../util'
import { ArtistContext } from '../contexts/ArtistContext'
import { Gender } from '../Consts'
import { TimeInterval } from '../types/TimeInterval'

export interface AgeRange {
  start: number
  end: number | null
}

export interface DemographicsAgeband<T = AgeRange | null> {
  gender: Gender
  ageRange: T
  value: number
}

interface TrackDemographicsResponse {
  demographics: Array<{
    dsp: 'apple' | 'spotify'
    ageBands: DemographicsAgeband[]
  }>
}

export function useTrackDemographics(
  isrc: string,
  countryCode: string,
  timeInterval: TimeInterval
) {
  const user = useContext(UserContext)
  const artist = useContext(ArtistContext)
  const { startDate, endDate } = timeRangeDates(timeInterval)
  const search = new URLSearchParams(
    _.omitBy({ startDate, endDate, countryCode }, _.isNil)
  ).toString()
  const path = `api/artists/${artist.sonyArtistId}/track/${isrc}/demographics?${search}`
  const response = useNetwork<TrackDemographicsResponse>(path, user, () => {})

  return {
    ...response,
  }
}
