import pipe from 'lodash/fp/pipe'
import orderBy from 'lodash/fp/orderBy'
import sumBy from 'lodash/fp/sumBy'
import uniqBy from 'lodash/fp/uniqBy'

import type { Videos, Video } from './getVideos'
import { getVideos } from './getVideos'

const calculateDuration = (videos: Videos) => {
  const durationMs = pipe(
    orderBy(({ quality }: Video) => Number(quality), 'desc'),
    uniqBy(({ period }: Video) => period),
    sumBy(({ duration }: Video) => duration),
  )(videos)
  return durationMs / 1000
}

/**
 * Временный способ получения длительности матча
 */
export const getFullMatchDuration = async (...args: Parameters<typeof getVideos>) => {
  const videos = await getVideos(...args)
  return calculateDuration(videos)
}
