/* eslint-disable camelcase */
/* eslint-disable import/prefer-default-export */
import { zeroPadding } from './schedule';

function isValidDate(d) {
  return d instanceof Date && !Number.isNaN(d);
}

export function convertTimeZone(event) {
  if (!event || !event.date || !event.date.time) {
    return event;
  }
  const timeArr = event.date.time.split(':');

  // ecmascript has month ranges between 0 - 11, that's why we do -1 to month_number
  const currentTimeZoneDate = new Date(
    Date.UTC(
      event.date.year_number,
      zeroPadding(event.date.month_number - 1, 2),
      zeroPadding(event.date.day_number, 2),
      timeArr[0],
      timeArr[1]
    )
  );

  if (!isValidDate(currentTimeZoneDate)) return event;

  const time = `${zeroPadding(currentTimeZoneDate.getHours(), 2)}:${zeroPadding(
    currentTimeZoneDate.getMinutes(),
    2
  )}`;

  // in case the utc is 23:00, but user's timezone can get 00:00 so update the date object.
  const day_number = zeroPadding(currentTimeZoneDate.getDate(), 2);
  const month_number = zeroPadding(currentTimeZoneDate.getMonth() + 1, 2);
  const date = `${day_number}-${month_number}-${zeroPadding(currentTimeZoneDate.getFullYear(), 2)}`;

  const dateAttrs = {
    date: {
      ...event.date,
      time,
      month_number,
      day_number,
      date,
    },
  };

  return { ...event, ...dateAttrs };
}

function updateSchedule(schedule) {
  if (!schedule) {
    return {};
  }

  return Object.keys(schedule).reduce((acc, key) => {
    const { tournaments } = schedule[key] || {};
    if (!tournaments && ['soccer', 'handball', 'tennis', 'cricket', 'darts'].includes(key)) {
      const value = updateSchedule(schedule[key]);
      acc[key] = value;
      return acc;
    }
    // else if schedule is normal format
    const formattedTournaments =
      tournaments &&
      Object.keys(tournaments).reduce((tournamentAcc, currentTournamentKey) => {
        const league = tournaments[currentTournamentKey];
        const formattedEvents = league.events.map((event) => convertTimeZone(event));

        tournamentAcc[currentTournamentKey] = { ...league, events: formattedEvents };
        return tournamentAcc;
      }, {});
    acc[key] = { ...schedule[key], tournaments: formattedTournaments };
    return acc;
  }, {});
}

export function updateAllTimezones(relation) {
  const relationSchedule = relation?.schedule;
  const relationFeaturedEvents = relation?.featured_events;
  const relationShowcasedEvents = relation?.showcased_events;

  // formated timezone schedule
  const schedule = updateSchedule(relationSchedule);

  // formated timezone featured events
  const featured_events = relationFeaturedEvents?.map((event) => convertTimeZone(event)) || [];

  // formated timezone showcased events
  const showcased_events = relationShowcasedEvents?.map((event) => convertTimeZone(event)) || [];

  // format timezone for relation.event
  const event = convertTimeZone(relation?.event);

  const updatedObject = { ...relation, schedule, featured_events, showcased_events };
  if (event) {
    updatedObject.event = event;
  }

  return updatedObject;
}
