<?php

namespace Rdgcorp\Blocks\TeamSchedules;

require __DIR__ . '/utils/CacheManager.php';
require __DIR__ . '/utils/MasterFeedApiConsumer.php';

use Rdgcorp\Blocks\TeamSchedules\Utils\CacheManager;
use Rdgcorp\Blocks\TeamSchedules\Utils\MasterFeedApiConsumer;

class BlockDataLoader
{
    private CacheManager $cacheManager;

    private MasterFeedApiConsumer $masterFeedApiConsumer;

    private string $cacheFile;

    private string $apiKey;

    private ?array $schedulesLog = null;

    public function __construct()
    {
        $this->cacheFile = (wp_upload_dir()['basedir']) . '/rdg-blocks/cache/team_schedules.json';
        $this->apiKey = 'KVbgULzIPQRXsREsbzrCFqdydvweEJUVUobxDZBsTOIzKNsNXW';

        $this->cacheManager = new CacheManager($this->cacheFile);
        $this->masterFeedApiConsumer = new MasterFeedApiConsumer($this->apiKey);
    }

    public function getApiKey(): string
    {
        return $this->apiKey;
    }

    public function getSports(): array
    {
        $cacheKey = 'sports';

        $data = $this->cacheManager->retrieveCache($cacheKey);

        if ($data) {
            return $data;
        }

        $data = $this->masterFeedApiConsumer->getSports();

        $this->cacheManager->storeCache($cacheKey, $data);

        return $data;
    }

    public function getLeagues(string $sportId): array
    {
        $cacheKey = 'leagues-sport-' . $sportId;

        $data = $this->cacheManager->retrieveCache($cacheKey);

        if ($data) {
            return $data;
        }

        $data = $this->masterFeedApiConsumer->getLeagues($sportId);

        $this->cacheManager->storeCache($cacheKey, $data);

        return $data;
    }

    public function getTeams(string $leagueId): array
    {
        $cacheKey = 'teams-league-' . $leagueId;

        $data = $this->cacheManager->retrieveCache($cacheKey);

        if ($data) {
            return $data;
        }

        $data = $this->masterFeedApiConsumer->getTeams($leagueId);

        $this->cacheManager->storeCache($cacheKey, $data);

        return $data;
    }

    public function getSeasons(string $leagueId): array
    {
        $cacheKey = 'seasons-league-' . $leagueId;

        $data = $this->cacheManager->retrieveCache($cacheKey);

        if ($data) {
            return $data;
        }

        $data = $this->masterFeedApiConsumer->getSeasons($leagueId);

        $this->cacheManager->storeCache($cacheKey, $data);

        return $data;
    }

    public function getSchedules(string $teamId, string $seasonId): ?array
    {
        $this->schedulesLog = [];

        if (!$this->masterFeedApiConsumer->hasMapper($teamId)) {
            $data = explode('/', $teamId);

            $this->schedulesLog[] = 'The selected sport (' . $data[2] . ')  does not have a schedule mapper configured';

            return null;
        }

        $cacheKey = 'schedules-team-' . $teamId . '-season-' . $seasonId;

        $data = $this->cacheManager->retrieveCache($cacheKey);

        $this->schedulesLog[] = 'Retrieving cache for team (' . $teamId . ') and season (' . $seasonId . ')...';
        $this->schedulesLog[] = $this->cacheManager->getLastLog();

        if (null !== $data) {
            $this->schedulesLog[] = 'Cache found. Process finished';

            return $data;
        }

        if ($this->cacheManager->getLastLog()['cache']['invalidated']) {
            $this->schedulesLog[] = 'Cache invalidated by lifetime';
        } else {
            $this->schedulesLog[] = 'Cache not found';
        }

        $this->schedulesLog[] = 'Loading data from API...';
        $this->schedulesLog[] = [
            'url' => 'http://masterfeed.shnadmin.com/feed/sportdirect/schedules',
            'method' => 'GET',
            'query' => [
                'key' => $this->apiKey,
                'team_id' => $teamId,
                'seasons_id' => $seasonId,
            ]
        ];

        $data = $this->masterFeedApiConsumer->getSchedules($teamId, $seasonId);

        $this->schedulesLog[] = 'Storing cache...';

        $this->cacheManager->storeCache($cacheKey, $data);

        $this->schedulesLog[] = $this->cacheManager->getLastLog();

        $this->schedulesLog[] = 'Data Found. Process finished';

        return $data;
    }

    public function getLastSchedulesLog(): ?array
    {
        return $this->schedulesLog;
    }
}
