import { RefObject } from 'react'

import findIndex from 'lodash/findIndex'

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

type Args = {
  from?: number,
  url: string,
  videoRef: RefObject<HTMLVideoElement>,
}

export const preparePlayer = ({
  from = 0,
  url,
  videoRef,
}: Args) => {
  const video = videoRef?.current
  if (!video) return

  // eslint-disable-next-line no-param-reassign
  video.src = url
  if (from) {
    video.currentTime = from
  }
  video.load()
}

export const findChapterByProgress = (chapters: Chapters, progressMs: number) => (
  findIndex(chapters, ({ endMs, startMs }) => (
    startMs <= progressMs && progressMs <= endMs
  ))
)

export const getNextPlayer = (player: Players): Players => (player + 1) % 2
