import { Interval } from 'date-fns'

import { DateData } from '../DateData'
import { streamsSummary } from '../streams'
import { Dsp } from '../types/types'
import { previousInterval as getPreviousInterval } from '../util/date'
import { NetworkError } from './useNetwork'

export type StreamsByDateResult = {
  streams?: DateData<number | null>[]
  error: NetworkError | null
}

export interface IntervalSummary {
  changeNumber: number
  changePercentage: number | null
  currentIntervalStreams: DateData<number | null>[]
  currentIntervalStreamsSum: number
  previousIntervalStreams: DateData<number | null>[]
  previousIntervalStreamsSum: number
  dsp?: Dsp | null
}

/**
 *
 * @param currentInterval
 * @returns Summary of entity streams/views and change for current and previous interval
 */
export function useEntityStreamsSummary(
  currentInterval: Interval,
  useEntityStreams: (interval: Interval) => StreamsByDateResult
): {
  data?: IntervalSummary
  error?: NetworkError | null
} {
  const previousInterval = getPreviousInterval(currentInterval)
  const currentIntervalResponse = useEntityStreams(currentInterval)

  const currentIntervalStreams = currentIntervalResponse.streams ?? null
  const previousIntervalResponse = useEntityStreams(previousInterval)

  if (currentIntervalResponse.error) {
    return { error: currentIntervalResponse.error }
  }

  if (previousIntervalResponse.error) {
    return { error: previousIntervalResponse.error }
  }

  const previousIntervalStreams = previousIntervalResponse.streams ?? null

  if (previousIntervalStreams !== null && currentIntervalStreams !== null) {
    return {
      data: streamsSummary(currentIntervalStreams, previousIntervalStreams),
    }
  } else {
    return { data: undefined }
  }
}
