<?php

namespace Rdgcorp\Blocks\TeamSchedules\Utils\Mappers;

class BaseballSchedulesMapper 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 season')) {
                    $type = 'Regular-Season';
                } else {
                    $type = 'Post-Season';
                }

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

        $data = [];

        foreach ($types as $key => $type) {
            if ('Post-Season' === $key) {
                $data[$key] = $type;
            } else {
                $weeks = [];

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

                $schedules = [];

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

                while (0 < count($weeks)) {
                    $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 {
                        $data[] = [
                            'week' => 'Week ' . $currentSeasonWeek,
                            'date' => 'BYE',
                            'opponent' => 'BYE',
                            'result' => 'BYE',
                        ];
                    }

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

                    $currentRealWeek++;
                    $currentSeasonWeek++;
                }

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

        return $data;
    }
}
