<?php

namespace AutoAdmin\Bundle\Media\Twig\Extension;

use AutoAdmin\Bundle\Media\Model\FileInterface;
use AutoAdmin\Bundle\Media\Model\ImageInterface;
use AutoAdmin\Bundle\Media\Service\PublicPathGenerator;
use Exception;
use Liip\ImagineBundle\Imagine\Cache\CacheManager;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Twig\TwigFunction;

class MediaExtension extends AbstractExtension
{
    public function __construct(
        private readonly PublicPathGenerator $publicPathGenerator,
        private readonly CacheManager $cache)
    {
    }

    /**
     * {@inheritdoc}
     */
    public function getFilters(): array
    {
        return [
            new TwigFilter('webp', [$this, 'webpFilter']),
        ];
    }

    public function getFunctions(): array
    {
        return [
            new TwigFunction('media_url', [$this, 'getMediaUrl']),
            new TwigFunction('media_is_image', [$this, 'isImage']),
            new TwigFunction('image_resize_url', [$this, 'getImageResizeUrl']),
        ];
    }

    public function isImage($media): bool
    {
        return $media instanceof ImageInterface;
    }

    public function getMediaUrl(FileInterface $mediaModel = null): ?string
    {
        return $this->publicPathGenerator->getMediaUrl($mediaModel);
    }

    public function getImageResizeUrl(
        ImageInterface $imageModel,
        int            $width,
        int            $height,
        array          $options = [],
                       $filter = 'default'
    ): string
    {
        return $this->publicPathGenerator->getResizedMediaPictureUrl($imageModel, $width, $height, $filter, $options);
    }

    /**
     * Gets the browser path for the image and filter to apply.
     */
    public function webpFilter(?string $path, string $filter = "default", array $config = [], ?string $resolver = null): ?string
    {
        if (empty($path)) {
            return '#null';
        }

        $urlImageWebp = "media/cache/" . $filter . parse_url($path, PHP_URL_PATH) . ".webp";

        if (file_exists($urlImageWebp)) {
            return "/" . $urlImageWebp;
        }

        try {
            $url = $this->cache->getBrowserPath(parse_url($path, PHP_URL_PATH), $filter, $config, $resolver);
        } catch (Exception $e) {
            /* return default path if webp filter is not configured in liip_imagine.yaml */
            $url = parse_url($path, PHP_URL_PATH);
        }

        if (!stripos($url, 'resolve') && !file_exists($url)) {
            $url = parse_url($path, PHP_URL_PATH);
        }

        return $url;
    }
}
