import { PROCEDURES, STATS_API_URL } from 'config'
import { callApi } from 'helpers'

const proc = PROCEDURES.get_match_watch

type Args = {
  fullMatchDuration?: number,
  matchId: number,
  sportType: number,
  withFullMatchDuration?: boolean,
}

export type Episode = {
  /** events count */
  c: number,

  /** 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,
  sportType,
}: Args): Promise<MatchPlaylists> => {
  const config = {
    body: {
      params: {
        match_id: matchId,
        sport_id: sportType,
      },
      proc,
    },
  }

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

  try {
    const playlist: Response = await callApi({
      config,
      url: `${STATS_API_URL}/data/stats`,
    })
    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,
  }
}
