<?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\Mostviewed\Block\Widget\Related;

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

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

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

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

    /**
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function afterGetImage(Related $subject, Image $result): Image
    {
        if (!$this->lazyConfig->getData(LazyConfig::IS_LAZY)) {
            return $result;
        }

        $imageUrl = [$result->getImageUrl()];
        $this->replaceByPatternApplier->execute(
            ProductGalleryReplace::REPLACE_PATTERN_GROUP,
            $imageUrl
        );
        $result->setImageUrl($imageUrl[0]);

        return $result;
    }
}
