<?php

namespace Rdgcorp\Blocks\TeamSchedules\Utils;

class CacheStack
{
    private bool $persist = false;

    private string $file;

    private array $stack = [];

    public function __construct(string $file)
    {
        $this->file = $file;

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

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

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

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

    public function getItem(string $key): ?array
    {
        $encodedKey = base64_encode($key);

        return $this->stack[$encodedKey];
    }

    public function setItem(string $key, array $data): void
    {
        $encodedKey = base64_encode($key);

        $this->stack[$encodedKey] = $data;

        $this->persist = true;
    }
}
