/* eslint-disable import/no-extraneous-dependencies */
/* eslint-disable default-case */
/* eslint-disable no-case-declarations */
/* eslint-disable no-undef */
/* eslint-disable no-continue */
/* eslint-disable no-restricted-syntax */
/* eslint-disable guard-for-in */
/* eslint-disable import/prefer-default-export */
/* eslint-disable no-async-promise-executor */

import { cloneDeep } from 'lodash';
import { sortByDate } from 'sports-util';
import {
  getStatisticsData,
  getOddsData,
  getEventDetailsData,
  getIncidentsData,
  getLineUpsData,
  getStandingsData,
  getRoundsData,
  getScheduleData,
  getHead2HeadsData,
} from '../../helpers/services';

export function getNextRound(data) {
  // Check for next future round first, if not past round
  const nextRound = [];
  const pastRounds = sortByDate(
    data.filter((x) => Date.parse(x.start_date) < new Date().valueOf()),
    false
  );
  const futureRounds = sortByDate(
    data.filter((x) => Date.parse(x.start_date) > new Date().valueOf())
  );

  nextRound.push(futureRounds.length ? futureRounds[0] : pastRounds[0]);

  return nextRound;
}

function getTournamentsData(tournaments) {
  return new Promise(async (resolve) => {
    const allTournaments = {};

    await Promise.all(
      tournaments.map(async (item) => {
        const standingsData = await getStandingsData(item.stage_id, 'en');
        const roundsData = await getRoundsData(item.stage_id, 'en');
        const nextRound = roundsData && (await getNextRound(roundsData));

        const scheduleData =
          nextRound &&
          nextRound.length > 0 &&
          (await getScheduleData(item.stage_id, nextRound[0].id, 'en'));

        let eventOddsData = null;
        if (scheduleData) {
          eventOddsData = await Promise.all(
            scheduleData.results.map(async (event) => {
              const { odds } = await getOddsData(event.id);
              const eventDetails = cloneDeep(event);
              eventDetails.day = new Date(event.start_date).getDate();
              eventDetails.odds = odds;
              return eventDetails;
            })
          );
        }

        Object.assign(allTournaments, {
          [item.stage_id]: {
            standings: standingsData,
            rounds: roundsData,
            events: eventOddsData,
          },
        });
      })
    );

    resolve(allTournaments);
  });
}

export async function getAPIData(page) {
  let res = '';

  switch (page?.relation_type) {
    case 'tournament':
      res = await getTournamentsData(page.relation.tournaments);
      break;
    case 'event':
      const operatorList =
        page.sections.header &&
        page.sections.header.modules &&
        page.sections.header.modules.length > 0 &&
        page.sections.header.modules[0].name === 'top_list'
          ? page.sections.header.modules[0].items[0].items
          : null;

      const eventStatisticsData = await getStatisticsData(page.relation.event.livegoals_v2_id);
      const eventDetailsData = await getEventDetailsData(page.relation.event.livegoals_v2_id, 'en');
      const oddsData = await getOddsData(page.relation.event.livegoals_v2_id, operatorList);
      const incidentsData = await getIncidentsData(page.relation.event.livegoals_v2_id, 'en');
      const lineUpsData = await getLineUpsData(page.relation.event.livegoals_v2_id, 'en');
      const head2headData = await getHead2HeadsData(page.relation.event.livegoals_v2_id, 'en');

      res = {
        odds: oddsData,
        details: eventDetailsData,
        statistics: eventStatisticsData,
        incidents: incidentsData,
        lineups: lineUpsData,
        head2head: head2headData,
      };
      break;
  }

  return {
    props: res,
  };
}
