import head from 'lodash/head'
import last from 'lodash/last'
import inRange from 'lodash/inRange'

import type { VideoBounds } from 'requests'

export const getHalfTime = (videoBounds: VideoBounds, currentTime: number) => {
  const firstBound = head(videoBounds)
  const lastBound = last(videoBounds)

  const matchSecond = (Number(firstBound?.s) || 0) + currentTime

  if (matchSecond > (Number(lastBound?.e) || 0)) {
    return {}
  }

  if (matchSecond < Number(videoBounds[1].s)) {
    return {
      period: 1,
      second: 1,
    }
  }

  let period = 1
  let second = 1

  for (let i = 1; i < videoBounds.length; i++) {
    const { e, s } = videoBounds[i]

    if (inRange(
      matchSecond,
      Number(s),
      Number(e) + 1,
    )) {
      period = i
      second = matchSecond - Number(videoBounds[i].s)
      break
    } else if (inRange(
      matchSecond,
      Number(e) + 1,
      Number(videoBounds[i + 1].s),
    )) {
      period = i + 1
      break
    }
  }

  return {
    period,
    second,
  }
}
