import { Interval } from 'date-fns'
import { NetworkError } from '../components/useNetwork'
import { DateData, sumDateData } from '../DateData'
import { periodToPeriodChangePercentage } from '../streams'
import { previousInterval as getPreviousInterval } from '../util/date'

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

export interface IntervalSummary {
  changeNumber: number
  changePercentage: number | null
  currentIntervalStreams: DateData<number | null>[]
  currentIntervalStreamsSum: number
}

/**
 *
 * @param entityId
 * @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: {
        changeNumber:
          sumDateData(currentIntervalStreams) -
          sumDateData(previousIntervalStreams),
        changePercentage: periodToPeriodChangePercentage({
          currentPeriodByDay: currentIntervalStreams.map(({ data }) => data),
          previousPeriodByDay: previousIntervalStreams.map(({ data }) => data),
        }),
        currentIntervalStreams: currentIntervalStreams,
        currentIntervalStreamsSum: sumDateData(currentIntervalStreams),
      },
    }
  } else {
    return { data: undefined }
  }
}
