<?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 Liip\ImagineBundle\Templating\FilterTrait;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Twig\TwigFunction;

class MediaExtension extends AbstractExtension
{
    use FilterTrait;

    private PublicPathGenerator $publicPathGenerator;

    public function __construct(PublicPathGenerator $generator, CacheManager $cache)
    {
        $this->publicPathGenerator = $generator;
        $this->cache = $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 $path;
        }

        $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;
    }
}
