<?php

namespace Rdgcorp\Blocks\TeamSchedules\Utils;

require 'CacheStack.php';

class CacheManager
{
    private CacheStack $cacheStack;

    public function __construct($cacheFile)
    {
        return $this->cacheStack = new CacheStack($cacheFile);
    }

    public function retrieveCache(string $key): ?array
    {
        $cache = $this->cacheStack->getItem($key);

        $currentDate = new \DateTime('now');
        $cacheUntilDate = new \DateTime($cache['until']);

        if ($currentDate >= $cacheUntilDate) {
            return null;
        }

        return $cache['data'];
    }

    public function storeCache(string $key, array $data, \DateTimeInterface $until = new \DateTime('now +1 day')): void
    {
        $cache = [
            'key' => $key,
            'date' => (new \DateTime('now'))->format('Y-m-d H:i:s'),
            'until' => $until->format('Y-m-d H:i:s'),
            'data' => $data,
        ];

        $this->cacheStack->setItem($key, $cache);
    }
}
