import isEmpty from 'lodash/isEmpty'

import {
  DATA_URL,
  PROCEDURES,
  SportTypes,
} from 'config'
import { callApi, getSportLexic } from 'helpers'

import { getFullMatchDuration } from './getFullMatchDuration'

const proc = PROCEDURES.ott_match_popup

type Args = {
  matchId: number,
  selectedActions: Array<number>,
  sportType: SportTypes,
  withFullMatchDuration?: boolean,
}

export type Episode = {
  /** episode end */
  e: number,

  /** match half/time */
  h: number,

  /** episode start */
  s: number,
}

export type Episodes = Array<Episode>

type PlaylistWithDuration = {
  data?: Episodes,
  dur?: number,
}

type Player = {
  dur: number,
  gk?: boolean,
  id: number,
  name_eng: string,
  name_rus: string,
  num: string,
  start?: boolean,
}

export type Players = Array<Player>

export type Lexics = {
  ball_in_play: number,
  full_game: number,
  goals: number,
  highlights: number,
  interview: number,
  players: number,
}

export type MatchPlaylists = {
  ball_in_play?: PlaylistWithDuration,
  full_game?: PlaylistWithDuration,
  goals?: PlaylistWithDuration,
  highlights?: PlaylistWithDuration,
  lexics: Lexics,
  players1: Players,
  players2: Players,
  score1: number,
  score2: number,
  state?: string,
}

type Response = {
  data?: MatchPlaylists,
}

export const getMatchPlaylists = async ({
  matchId,
  selectedActions,
  sportType,
  withFullMatchDuration,
}: Args) => {
  const actions = isEmpty(selectedActions) ? null : selectedActions

  const config = {
    body: {
      params: {
        _p_actions: actions,
        _p_match_id: matchId,
      },
      proc,
    },
  }

  const playlistPromise: Promise<Response> = callApi({
    config,
    url: `${DATA_URL}/${getSportLexic(sportType)}`,
  })

  const matchDurationPromise = withFullMatchDuration
    ? getFullMatchDuration(sportType, matchId)
    : Promise.resolve(undefined)

  const [playlist, fullMatchDuration] = await Promise.all(
    [playlistPromise, matchDurationPromise],
  )

  const full_game: PlaylistWithDuration = {
    data: [],
    dur: fullMatchDuration,
  }

  return playlist.data
    ? { ...playlist.data, full_game }
    : null
}
