<?php

namespace Rdgcorp\Blocks\TeamSchedules\Utils\Mappers;

abstract class AbstractScheduleMapper implements SchedulesMapperInterface
{
    private array $teams;

    public function __construct(array $teams)
    {
        $this->teams = $teams;
    }

    protected function getScheduleOpponent(string $homeTeamId, array $schedule): string
    {
        if ($schedule['home_team_id'] === $homeTeamId) {
            return $this->teams[$schedule['visitor_team_id']];

        }

        return $this->teams[$schedule['home_team_id']];
    }

    protected function getScheduleResult(string $homeTeamId, array $schedule): string
    {
        if ($schedule['home_team_id'] === $homeTeamId) {
            $teamRol = 'home';
            $opponentRol = 'away';
        } else {
            $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 (0 === count($stats)) {
            return 'TBD';
        }

        if ($stats[$teamRol] === $stats[$opponentRol]) {
            return 'T ' . $stats[$teamRol] . '-' . $stats[$opponentRol];
        }

        if ($stats[$teamRol] > $stats[$opponentRol]) {
            return 'W ' . $stats[$teamRol] . '-' . $stats[$opponentRol];
        }

        if ($stats[$teamRol] < $stats[$opponentRol]) {
            return 'L ' . $stats[$teamRol] . '-' . $stats[$opponentRol];
        }

        return 'Error';
    }
}
