import isEmpty from 'lodash/isEmpty'

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

const proc = PROCEDURES.ott_match_popup

type Args = {
  fullMatchDuration?: number,
  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 ({
  fullMatchDuration,
  matchId,
  selectedActions,
  sportType,
}: Args): Promise<MatchPlaylists> => {
  const actions = isEmpty(selectedActions) ? null : selectedActions

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

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

  try {
    const playlist: Response = await callApi({
      config,
      url: `${DATA_URL}/${getSportLexic(sportType)}`,
    })
    if (playlist.data) {
      return { ...playlist.data, full_game }
    }
  } catch {
    return {
      ball_in_play: {},
      full_game,
      goals: {},
      highlights: {},
      lexics: {},
      players1: [],
      players2: [],
      score1: 0,
      score2: 0,
    }
  }

  return {
    ball_in_play: {},
    full_game,
    goals: {},
    highlights: {},
    lexics: {},
    players1: [],
    players2: [],
    score1: 0,
    score2: 0,
  }
}
