import last from 'lodash/last'
import find from 'lodash/find'
import reduce from 'lodash/reduce'
import concat from 'lodash/concat'

import type { Episodes } from 'requests/getMatchPlaylists'
import type { MatchInfo } from 'requests/getMatchInfo'

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

import type { MatchPlaylistOption, PlaylistOption } from '../../types'
import { FULL_GAME_KEY } from '../../helpers/buildPlaylists'

export const FULL_MATCH_BOUNDARY = '0'

/**
 * Формирует эпизоды плейлиста Полный матч
 * API не выдает полный матч как плейлист, формируем на фронте
 * */
const getFullMatchChapters = (
  profile: MatchInfo,
  url: string,
  playlist: MatchPlaylistOption,
) => {
  const bound = find(profile?.video_bounds, { h: FULL_MATCH_BOUNDARY })

  const durationMs = (bound && !profile?.live)
    ? ((playlist.duration ?? 0) - Number(bound.s)) * 1000
    : (playlist.duration ?? 0) * 1000

  return [
    {
      duration: durationMs,
      endMs: durationMs,
      endOffsetMs: bound ? Number(bound.e) * 1000 : durationMs,
      index: 0,
      isFullMatchChapter: true,
      startMs: 0,
      startOffsetMs: bound ? Number(bound.s) * 1000 : 0,
      url,
    },
  ]
}

/**
 * Формирует эпизоды плейлистов матча и игроков
 * */
const getPlaylistChapters = (
  profile: MatchInfo,
  url: string,
  episodes: Episodes,
) => reduce(
  episodes,
  (
    acc: Chapters,
    episode,
    index,
  ) => {
    if (episode.s >= episode.e) return acc

    const bound = find(profile?.video_bounds, { h: String(episode.h) })
    const boundStart = bound ? Number(bound.s) : 0

    const episodeDuration = (episode.e - episode.s) * 1000
    const prevVideoEndMs = last(acc)?.endMs ?? 0

    const nextChapter: Chapter = {
      duration: episodeDuration,
      endMs: prevVideoEndMs + episodeDuration,
      endOffsetMs: (boundStart + episode.e) * 1000,
      index,
      startMs: prevVideoEndMs,
      startOffsetMs: (boundStart + episode.s) * 1000,
      url,
    }
    return concat(acc, nextChapter)
  },
  [],
)

type Args = {
  profile: MatchInfo,
  selectedPlaylist?: PlaylistOption,
  url: string,
}

/**
 * Формирует список эпизодов из выбранного плейлиста для плеера
 */
export const buildChapters = ({
  profile,
  selectedPlaylist,
  url,
}: Args): Chapters => {
  if (!selectedPlaylist) return []
  if (selectedPlaylist.id === FULL_GAME_KEY) {
    return getFullMatchChapters(
      profile,
      url,
      selectedPlaylist,
    )
  }
  return getPlaylistChapters(
    profile,
    url,
    selectedPlaylist.episodes,
  )
}
