<?php

namespace Rdgcorp\Blocks\TeamSchedules\Utils;

require __DIR__ . '/CacheFile.php';

class CacheManager
{
    private string $cacheDirectory;

    private ?array $log = null;

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

    public function retrieveCache(string $key): ?array
    {
        $cacheFile = new CacheFile($this->cacheDirectory, $key);

        $cache = $cacheFile->getCache();

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

        $this->log = [
            'file' => [
                'path' => $cacheFile->getFile(),
                'fileExist' => $cacheFile->fileExists(),
            ],
            'cache' => [
                'action' => 'retrieve',
                'invalidated' => !$cacheUntilDate || $currentDate > $cacheUntilDate,
                'data' => $cache,
            ]
        ];

        if (!$cache) {
            return null;
        }

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

        return $cache['data'];
    }

    public function storeCache(string $key, array $data, \DateTimeInterface $until = new \DateTime('tomorrow')): void
    {
        $cacheFile = new CacheFile($this->cacheDirectory, $key);

        $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' => $cacheFile->getFile(),
                'fileExist' => $cacheFile->fileExists(),
            ],
            'cache' => [
                'action' => 'store',
                'data' => $cache,
            ]
        ];

        $cacheFile->setCache($cache);
    }

    public function deleteAllCacheFiles(): void
    {
        if (!file_exists($this->cacheDirectory)) {
            return;
        }

        foreach (glob($this->cacheDirectory . '/*.*') as $filename) {
            unlink($filename);
        }
    }

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