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,
}

type PlaylistData = {
  /** episode end */
  e: number,

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

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

type Playlist = {
  data: Array<PlaylistData>,
  dur: number,
}

type Player = {
  id: number,
  name_eng: string,
  name_rus: string,
  num: string,
}

export type Players = Array<Player>

export type MatchPlaylists = {
  ball_in_play: Playlist,
  fullMatchDuration: number,
  goals: Playlist,
  highlights: Playlist,
  players1: Players,
  players2: Players,
}

type Response = {
  data?: MatchPlaylists,
}

export const getMatchPlaylists = async ({
  matchId,
  selectedActions,
  sportType,
}: Args) => {
  const config = {
    body: {
      params: {
        _p_actions: selectedActions,
        _p_match_id: matchId,
      },
      proc,
    },
  }

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

  const matchDurationPromise = getFullMatchDuration(sportType, matchId)

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

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