<?php

namespace Rdgcorp\Blocks\TeamSchedules\Utils;

class CacheFile
{
    private bool $persist = false;

    private string $file;

    private array $cache = [];

    public function __construct(string $directory, string $key)
    {
        $this->file = $directory . '/' . $this->encodeKey($key) . '.json';

        if ($this->fileExists()) {
            $content = file_get_contents($this->file);

            $this->cache = json_decode($content, true);
        }
    }

    public function __destruct()
    {
        if ($this->persist) {
            $cacheDirectory = pathinfo($this->file)['dirname'];

            if (!file_exists($cacheDirectory)) {
                mkdir(pathinfo($this->file)['dirname'], 0777, true);
            }

            file_put_contents($this->file, json_encode($this->cache));
        }
    }

    public function getFile(): string
    {
        return $this->file;
    }

    public function fileExists(): bool
    {
        return file_exists($this->file);
    }

    public function encodeKey(string $key): string
    {
        return base64_encode($key);
    }

    public function getCache(): ?array
    {
        return $this->cache;
    }

    public function setCache(?array $cache): void
    {
        $this->cache = $cache;

        $this->persist = true;
    }
}
