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

  let period = 1
  let second = 1

  if (firstBound === lastBound || matchSecond < (Number(videoBounds[1]?.s || 0))) {
    return {
      period,
      second,
    }
  }

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

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

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

  return {
    period,
    second,
  }
}
