<?php

namespace Rdgcorp\Blocks\TeamSchedules\Utils;

require __DIR__ . '/CacheStack.php';

class CacheManager
{
    private CacheStack $cacheStack;

    private ?array $log = null;

    public function __construct($cacheFile)
    {
        $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']);

        $this->log = [
            'file' => [
                'path' => $this->cacheStack->getFile(),
                'fileExist' => $this->cacheStack->fileExists(),
                'itemsCount' => $this->cacheStack->countItems(),
            ],
            'cache' => [
                'cacheKey' => $this->cacheStack->encodeKey($key),
                'action' => 'retrieve',
                'cacheExist' => $this->cacheStack->issetItem($key),
                'invalidated' => $currentDate > $cacheUntilDate,
                'data' => $cache,
            ]
        ];

        if (!$cache) {
            return null;
        }

        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->log = [
            'file' => [
                'path' => $this->cacheStack->getFile(),
                'fileExist' => $this->cacheStack->fileExists(),
                'itemsCount' => $this->cacheStack->countItems(),
            ],
            'cache' => [
                'key' => $this->cacheStack->encodeKey($key),
                'cacheExist' => $this->cacheStack->issetItem($key),
                'action' => 'store',
                'data' => $cache,
            ]
        ];

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

    public function getLastLog(): ?array
    {
        return $this->log;
    }
}
