import keys from 'lodash/keys'
import uniq from 'lodash/uniq'
import orderBy from 'lodash/orderBy'
import includes from 'lodash/includes'

import { useLocalStore } from 'hooks'

import type { Chapters } from '../types'

const getVideoQualities = (chapters: Chapters) => {
  const qualities = uniq(keys(chapters[0]?.urls))
  return orderBy(
    qualities,
    Number,
    'desc',
  )
}

export const useVideoQuality = (chapters: Chapters) => {
  const videoQualities = getVideoQualities(chapters)

  const qualityValidator = (localStorageQuality: string) => (
    includes(videoQualities, localStorageQuality)
  )

  const [selectedQuality, setSelectedQuality] = useLocalStore({
    // по умолчанию наилучшее качество
    defaultValue: videoQualities[0],
    key: 'player_quality',
    validator: qualityValidator,
  })

  return {
    selectedQuality,
    setSelectedQuality,
    videoQualities,
  }
}
