<?php

declare(strict_types=1);

/**
 * @author Amasty Team
 * @copyright Copyright (c) Amasty (https://www.amasty.com)
 * @package Lazy Load for Magento 2 (System)
 */

namespace Amasty\LazyLoad\Plugin\Catalog\Model\ProductRender\Image;

use Amasty\LazyLoad\Model\Output\LazyConfig\LazyConfig;
use Amasty\LazyLoad\Plugin\Catalog\Block\Product\View\Gallery\ProductGalleryReplace;
use Amasty\PageSpeedTools\Model\Image\ReplaceByPatternApplier;
use Magento\Catalog\Model\ProductRender\Image;

class RecentlyViewedImageReplace
{
    /**
     * @var ReplaceByPatternApplier
     */
    private ReplaceByPatternApplier $replaceByPatternApplier;

    /**
     * @var LazyConfig
     */
    private LazyConfig $lazyConfig;

    public function __construct(
        ReplaceByPatternApplier $replaceByPatternApplier,
        LazyConfig $lazyConfig
    ) {
        $this->replaceByPatternApplier = $replaceByPatternApplier;
        $this->lazyConfig = $lazyConfig;
    }

    /**
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function beforeSetUrl(Image $subject, $url): array
    {
        if (!$this->lazyConfig->getData(LazyConfig::IS_LAZY)) {
            return [$url];
        }

        $url = [$url];
        $this->replaceByPatternApplier->execute(
            ProductGalleryReplace::REPLACE_PATTERN_GROUP,
            $url
        );

        return $url;
    }
}
