<?php

namespace Rdgcorp\Blocks\TeamSchedules\Utils;

require __DIR__ . '/../MasterFeed/vendor/autoload.php';

use Rdgcorp\MasterFeed\MasterFeed;

class MasterFeedApiConsumer
{
    private MasterFeed $masterFeed;

    public function __construct(string $token)
    {
        $this->masterFeed = new MasterFeed($token);
    }

    public function getSports(): array
    {
        $data = [];

        foreach ($this->masterFeed->getDirectSports() as $sport) {
            $data[$sport['id']] = $sport['name'];
        }

        return $data;
    }

    public function getLeagues(?string $sportId = null): array
    {
        $data = [];

        foreach ($this->masterFeed->getDirectLeagues($sportId) as $league) {
            $data[$league['id']] = $league['name'];
        }

        return $data;
    }

    public function getTeams(?string $leagueId = null): array
    {
        $data = [];

        foreach ($this->masterFeed->getDirectTeams($leagueId) as $team) {
            $data[$team['id']] = $team['name'];

            if (!ctype_upper($team['nickname']) && !str_contains(strtolower($team['name']), strtolower($team['nickname']))) {
                $data[$team['id']] .= ' ' . $team['nickname'];
            }
        }

        return $data;
    }

    public function getSeasons(?string $leagueId = null): array
    {
        $data = [];

        foreach ($this->masterFeed->getDirectSeasons($leagueId) as $season) {
            $data[$season['id']] = $season['name'];
        }

        return $data;
    }

    public function getSchedules(?string $teamId = null, ?string $seasonId = null): array
    {
        $teams = $this->getTeams();

        $scheduleTypes = [];

        foreach ($this->masterFeed->getDirectSchedules($teamId, $seasonId) as $schedule) {
            if ($schedule['home_team_id'] === $teamId) {
                $opponent = $teams[$schedule['visitor_team_id']];

                $teamRol = 'home';
                $opponentRol = 'away';
            } else {
                $opponent = $teams[$schedule['home_team_id']];

                $teamRol = 'away';
                $opponentRol = 'home';
            }

            $stats = [];

            foreach ($schedule['stats'] as $stat) {
                $stats[strtolower($stat['side'])] = (string)$stat['value'];
            }

            if (1 === count($stats)) {
                if (!isset($stats['home'])) {
                    $stats['home'] = 0;
                }

                if (!isset($stats['away'])) {
                    $stats['away'] = 0;
                }
            }

            if (2 == count($stats)) {
                if ($stats[$teamRol] === $stats[$opponentRol]) {
                    $result = 'T ' . $stats[$teamRol] . '-' . $stats[$opponentRol];
                } elseif ($stats[$teamRol] > $stats[$opponentRol]) {
                    $result = 'W ' . $stats[$teamRol] . '-' . $stats[$opponentRol];
                } else {
                    $result = 'L ' . $stats[$teamRol] . '-' . $stats[$opponentRol];
                }
            } else {
                $result = 'TBD';
            }

            $date = new \DateTime($schedule['start_date']);

            if (str_starts_with(strtolower($schedule['type']), 'pre-season')) {
                $type = 'Pre-Season';
            } elseif (str_starts_with(strtolower($schedule['type']), 'week')) {
                $type = 'Regular-Season';
            } else {
                $type = 'Post-Season';
            }

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

        $data = [];

        foreach ($scheduleTypes as $scheduleTypeKey => $scheduleType) {
            ksort($scheduleType);

            foreach ($scheduleType as $day) {
                foreach ($day as $schedule) {
                    if (str_starts_with($schedule['type'], 'Pre-Season ')) {
                        $schedule['type'] = str_replace('Pre-Season ', '', $schedule['type']);
                    }

                    $data[$scheduleTypeKey][] = $schedule;
                }
            }
        }

        foreach ($data as $type => $schedules) {
            if ('Post-Season' !== $type) {
                $weeks = [];

                foreach ($schedules as $schedule) {
                    $week = (int)str_replace('Week ', '', $schedule['type']);
                    $weeks[$week][] = $schedule;
                }

                $schedules = [];

                for ($i = 1; 0 < count($weeks); $i++) {
                    if (isset($weeks[$i])) {
                        foreach ($weeks[$i] as $schedule) {
                            $schedules[] = $schedule;
                        }

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

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

        return $data;
    }
}
