<?php


namespace AutoAdmin\Bundle\Core\Helper;

use Exception;

class CacheSuffixHelper
{
    protected string $projectDirectory;

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

    public function refreshSuffixFile(): bool
    {
        $handle = fopen($cacheSuffixFilePath = $this->getCacheSuffixPath(), 'w+b');

        if ($handle === false) {
            throw new Exception(sprintf('Could not open file "%s"', $cacheSuffixFilePath));
        } else {
            $suffix = $this->generate();
            $status = fwrite($handle, $suffix);
            if ($status === false) {
                throw new Exception(sprintf('Could write file "%s"', $cacheSuffixFilePath));
            }
        }

        return true;
    }

    public function getCacheSuffixPath(): string
    {
        return $this->projectDirectory . DIRECTORY_SEPARATOR . '.cache_suffix';
    }

    public function generate(): string
    {
        return substr(uniqid('', true), 0, 6);
    }

    public function getCacheSuffix(): string
    {
        $suffix = '';

        if (file_exists($path = $this->getCacheSuffixPath())) {
            $suffix = file_get_contents($path);
        }

        return $suffix;
    }
}
