<?php declare(strict_types=1);

namespace App\Engine\Literature;

readonly class LiteratureProvider
{

    public const CACHE_TTL = 3600;

    public function __construct(
        private \App\Engine\Literature\LiteratureRepository $literatureRepository,
        private \Symfony\Contracts\Cache\CacheInterface           $fileAdapterCache,
    ) {
    }

    /**
     * @return array<int, \App\Engine\Literature\PieceOfLiterature>
     */
    public function provideCached(): array
    {
        return $this->fileAdapterCache->get(self::getCacheKey(), function (\Symfony\Component\Cache\CacheItem $item) {
            $item->expiresAfter(self::CACHE_TTL);
            return $this->provide();
        });
    }

    public static function getCacheKey(): string
    {
        return "CachedLiterature";
    }

    /**
     * @return array<int, \App\Engine\Literature\PieceOfLiterature>
     */
    public function provide(): array
    {
        $literature = [];
        $literatureEntities = $this->literatureRepository->loadAll(limit: $this->getLimit());
        foreach ($literatureEntities as $literatureEntity) {
            $literature[] = new PieceOfLiterature(
                title: $literatureEntity->getTitle(),
                pictureHtml: $this->createPictureHtml($literatureEntity),
                text: $literatureEntity->getText(),
                link: $literatureEntity->getUrl(),
            );
        }

        return $literature;
    }

    protected function createPictureHtml(\App\Engine\Literature\Literature $literature): string
    {
        return \App\Engine\Thumbnail\Thumbnail::create()
            ->fromRelativePath($literature->getImage())
            ->width(577)
            ->height(474)
            ->sizeOperation(\App\Engine\Thumbnail\SizeOperation::CONTAIN)
            ->alt($literature->getTitle())
            ->getPictureHtmlTag();
    }

    protected function getLimit(): int
    {
        return 4; // Nastaveno podle grafiky pro komponentu sdílenou napříč stránkami.
    }

}