<?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 ($this->fileExists()) {
            $content = file_get_contents($this->file);

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

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

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

    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 countItems(): int
    {
        return count($this->stack);
    }

    public function issetItem(string $key): bool
    {
        return isset($this->stack[$this->encodeKey($key)]);
    }

    public function getItem(string $key): ?array
    {
        return $this->stack[$this->encodeKey($key)];
    }

    public function setItem(string $key, array $data): void
    {
        $this->stack[$this->encodeKey($key)] = $data;

        $this->persist = true;
    }
}
