<?php
declare(strict_types=1);

namespace App\Service\Twig;

use App\Entity\Core\File;
use App\Service\File\Exception\FileNotFoundException;
use App\Service\File\FileManager;
use App\Service\Utils\Path;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

/**
 * Add new Twig methods and filters to manipulate assets
 *
 * This is particularly useful for exports, since wkhtmltoX can't resolve partial paths for assets, or download
 * files from the Opentalent API (the non-public ones at least)
 *
 * // TODO: à voir si c'est bien à sa place parmi les services
 */
class AssetsExtension extends AbstractExtension
{
    public function __construct(
        readonly private FileManager $fileManager
    )
    {}

    public function getFunctions(): array
    {
        return [
            new TwigFunction('absPath', [$this, 'absPath']),
            new TwigFunction('toBase64Src', [$this, 'toBase64Src']),
        ];
    }

    /**
     * Return the absolute path of the given file in the public directory
     *
     * Usage :
     *
     *      <img src="{{ absPath('images/logo.png') }}"/>
     *
     * @param string $partialPath
     * @return string
     */
    public function absPath(string $partialPath): string
    {
        return Path::join(Path::getProjectDir(), 'public', $partialPath);
    }

    /**
     * Return the src of an image as a base64 content
     *
     * Usage :
     *
     *      <img src="{{ toBase64Src((licence.logo) }}"/>
     *
     * @param File $file
     * @return string
     * @throws FileNotFoundException
     */
    public function toBase64Src(File $file): string
    {
        return 'data:' . $file->getMimeType() . ';base64,' . base64_encode($this->fileManager->read($file));
    }
}
