<?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)
 *
 */
class AssetsExtension extends AbstractExtension
{
    public function __construct(
        readonly private FileManager $fileManager
    )
    {}

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

    /**
     * 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);
    }

    /**
     * Retourne l'URL d'accès à une image contenu dans une File
     *
     * Usage :
     *
     *      <img src="{{ fileImagePath((licence.logo, 'sm') }}"/>
     *
     * @param File $file
     * @return string
     * @throws FileNotFoundException
     */
    public function fileImagePath(File $file, $size): string
    {
        return $this->fileManager->readImage($file, $size, true);
    }
}
