import map from 'lodash/fp/map'
import pipe from 'lodash/fp/pipe'
import size from 'lodash/fp/size'
import slice from 'lodash/fp/slice'

import type { Chapters, Chapter } from 'features/StreamPlayer/types'

const calculateChapterProgress = (progress: number, chapter: Chapter) => (
  Math.min(progress * 100 / chapter.duration, 100)
)

type Args = {
  activeChapterIndex: number,
  chapters: Chapters,
  loadedProgress: number,
  playedProgress: number,
  videoDuration: number,
}

export const calculateChapterStyles = ({
  activeChapterIndex,
  chapters,
  loadedProgress,
  playedProgress,
  videoDuration,
}: Args) => {
  const playedChapters = pipe(
    slice(0, activeChapterIndex),
    map((chapter: Chapter) => ({
      ...chapter,
      loaded: 100,
      played: 100,
      width: chapter.duration * 100 / videoDuration,
    })),
  )(chapters)

  const comingChapters = pipe(
    slice(activeChapterIndex + 1, size(chapters)),
    map((chapter: Chapter) => ({
      ...chapter,
      loaded: 0,
      played: 0,
      width: chapter.duration * 100 / videoDuration,
    })),
  )(chapters)

  const chapter = chapters[activeChapterIndex]

  const activeChapter = {
    ...chapter,
    loaded: calculateChapterProgress(loadedProgress, chapter),
    played: playedProgress * 100 / videoDuration,
    width: chapter.isFullMatchChapter
      ? 100
      : chapter.duration * 100 / videoDuration,
  }
  return [
    ...playedChapters,
    activeChapter,
    ...comingChapters,
  ]
}
