<?php

declare(strict_types=1);

/**
 * @author Colinet Julien
 */

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Twig;

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Filesystem\Filesystem;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;

class FileExtension extends AbstractExtension
{
    public function __construct(
        private Filesystem $filesystem,
        private string $kernelProjectDir,
    ) {
    }

    public function getFilters(): array
    {
        return [
            new TwigFilter('file_path', [$this, 'filePathFilter']),
            new TwigFilter('image_path', [$this, 'imagePathFilter']),
        ];
    }

    public function filePathFilter(string $path): string
    {
        return $this->publicPath(
            $this->filesystem->absolutePath('file', $path)
        );
    }

    public function imagePathFilter(string $path): string
    {
        return $this->publicPath(
            $this->filesystem->absolutePath('image', $path)
        );
    }

    public function filePathAbsoluteFilter(string $path): string
    {
        return $this->filesystem->absolutePath('file', $path);
    }

    public function imagePathAbsoluteFilter(string $path): string
    {
        return $this->filesystem->absolutePath('image', $path);
    }

    private function publicPath(string $absolutePath): string
    {
        return str_replace(
            $this->kernelProjectDir.'/public',
            '',
            $absolutePath
        );
    }
}
