import { useContext } from 'react'

import { useGet } from '../components/Network'
import { ArtistContext } from '../contexts/ArtistContext'
import { UserContext } from '../contexts/UserContext'
import { Product } from '../types/Product'
import { TrackWithStreamsByDspAndDate } from '../types/types'
import { intervalDates } from '../util'
import { useNetwork } from './useNetwork'

export interface ProductListResponse {
  products: Product[]
}

export function useProducts() {
  const artist = useContext(ArtistContext)
  const user = useContext(UserContext)

  const { data, showToast, error, retry, refreshing } =
    useNetwork<ProductListResponse>(
      useGet(`api/artists/${artist.sonyArtistId}/products`, user)
    )

  const albums = data?.products
    ? data.products.filter(
        ({ productVersion }) =>
          productVersion !== null &&
          productVersion.configCatKey === 'C' && // Only display products of category C
          productVersion.isProductFamilyHead && // Filter out multiple variants of the same album that are not the product family head
          productVersion.mainArtistId === artist.sonyArtistId // Filter out collections that contain various artists
      )
    : null

  return { data, albums, showToast, error, retry, refreshing }
}

export interface ProductResponse {
  product: Product
  streams: TrackWithStreamsByDspAndDate[]
}

export function useProduct(productId: string, interval: Interval) {
  const user = useContext(UserContext)
  const artist = useContext(ArtistContext)
  const { startDate, endDate } = intervalDates(interval)

  return useNetwork<ProductResponse>(
    useGet(
      `api/artists/${artist.sonyArtistId}/products/${productId}` +
        `?startDate=${startDate}&endDate=${endDate}`,
      user
    )
  )
}
