<?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\PromoBanners\Block\Banner;

use Amasty\ImageOptimizer\Plugin\Catalog\Block\Product\View\Gallery\ProductGalleryReplace;
use Amasty\LazyLoad\Model\Output\LazyConfig\LazyConfig;
use Amasty\LazyLoad\Model\Output\LazyConfig\LazyConfigFactory;
use Amasty\PageSpeedTools\Model\Image\ReplaceByPatternApplier;
use Amasty\PromoBanners\Block\Banner;

class ReplaceImg
{
    /**
     * @var LazyConfig
     */
    private $lazyConfig;

    /**
     * @var ReplaceByPatternApplier
     */
    private $replaceByPatternApplier;

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

    /**
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function afterGetImageUrl(
        Banner $subject,
        string $result
    ): string {
        $resultArray[] = $result;
        if (!empty($result) && $this->lazyConfig->getData(LazyConfig::IS_LAZY)) {
            $this->replaceByPatternApplier->execute(
                ProductGalleryReplace::REPLACE_PATTERN_GROUP,
                $resultArray
            );
        }

        return $resultArray[0];
    }
}
