<?php

namespace Rdgcorp\Blocks\TeamSchedules\Utils\Mappers;

class SoccerSchedulesMapper extends AbstractScheduleMapper
{
    public function getMappedData($homeTeamId, $rawSchedules): array
    {
        $days = [];

        foreach ($rawSchedules as $schedule) {
            $date = new \DateTime($schedule['start_date']);

            $days[(int)$date->format('Ymd')][] = [
                'type' => $schedule['type'],
                'date' => $date->format('D d/m/Y'),
                'opponent' => $this->getScheduleOpponent($homeTeamId, $schedule),
                'result' => $this->getScheduleResult($homeTeamId, $schedule),
            ];
        }

        ksort($days);

        $types = [];

        foreach ($days as $day) {
            foreach ($day as $schedule) {
                if (str_starts_with(strtolower($schedule['type']), 'pre-season')) {
                    $type = 'Pre-Season';
                } elseif (str_starts_with(strtolower($schedule['type']), 'regular') ||
                    str_starts_with(strtolower($schedule['type']), 'group stage') ||
                    str_starts_with(strtolower($schedule['type']), 'round of') ||
                    str_starts_with(strtolower($schedule['type']), 'quarter-finals') ||
                    str_starts_with(strtolower($schedule['type']), 'semi-finals') ||
                    str_starts_with(strtolower($schedule['type']), 'finals')) {
                    $type = 'Regular-Season';
                } else {
                    $type = 'Post-Season';
                }

                $types[$type][] = $schedule;
            }
        }

        $data = [];

        foreach ($types as $key => $type) {
            if ('Post-Season' === $key || str_starts_with(strtolower($type[0]['type']), 'group stage') ||
                str_starts_with(strtolower($type[0]['type']), 'round of') ||
                str_starts_with(strtolower($type[0]['type']), 'quarter-finals') ||
                str_starts_with(strtolower($type[0]['type']), 'semi-finals') ||
                str_starts_with(strtolower($type[0]['type']), 'finals')) {
                $data[$key] = $type;
            } else {
                $weeks = [];

                foreach ($type as $schedule) {
                    $weeks[(int)(\Datetime::createFromFormat('D d/m/Y', $schedule['date']))->format('YW')][] = $schedule;
                }

                $schedules = [];

                $loopCounter = 0;
                $currentSeasonWeek = 1;
                $currentRealWeek = (int)substr(array_key_first($weeks), 4);
                $currentRealYear = (int)substr(array_key_first($weeks), 0, 4);

                while (0 < count($weeks)) {
                    if (500 < $loopCounter) {
                        throw new \Exception('Maximum loop exceeded');
                    }

                    $i = (int)($currentRealYear . str_pad($currentRealWeek, 2, '0', STR_PAD_LEFT));

                    if (isset($weeks[$i])) {
                        foreach ($weeks[$i] as $schedule) {
                            $schedule['type'] = 'Week ' . $currentSeasonWeek;
                            $schedules[] = $schedule;
                        }

                        unset($weeks[$i]);
                    } else {
                        $schedules[] = [
                            'type' => 'Week ' . $currentSeasonWeek,
                            'date' => 'BYE',
                            'opponent' => 'BYE',
                            'result' => 'BYE',
                        ];
                    }

                    if (52 === (int)$currentRealWeek) {
                        $currentRealWeek = 0;
                        $currentRealYear++;
                    }

                    $loopCounter++;
                    $currentRealWeek++;
                    $currentSeasonWeek++;
                }

                $data[$key] = $schedules;
            }
        }

        return $data;
    }
}
