<?php

declare(strict_types=1);

namespace FiloBlu\Refilo\Model\Product\Image;

use Magento\Catalog\Model\Product\Image\ParamsBuilder;
use Magento\Catalog\Model\View\Asset\ImageFactory;
use Magento\Catalog\Model\View\Asset\PlaceholderFactory;
use Magento\Framework\View\ConfigInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;

/**
 *
 */
class UrlBuilder extends \Magento\Catalog\Model\Product\Image\UrlBuilder {

    /**
     *
     */
    const XML_WEB_REFILO_CDN_REFILO_STOREFRONT_CDN_URL = 'web/refilo_cdn/refilo_storefront_cdn_url';

    /**
     * @var
     */
    private $scopeConfig;

    /**
     * @param \Magento\Framework\View\ConfigInterface $presentationConfig
     * @param \Magento\Catalog\Model\Product\Image\ParamsBuilder $imageParamsBuilder
     * @param \Magento\Catalog\Model\View\Asset\ImageFactory $viewAssetImageFactory
     * @param \Magento\Catalog\Model\View\Asset\PlaceholderFactory $placeholderFactory
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
     */
    public function __construct(
        ConfigInterface $presentationConfig,
        ParamsBuilder $imageParamsBuilder,
        ImageFactory $viewAssetImageFactory,
        PlaceholderFactory $placeholderFactory,
        ScopeConfigInterface $scopeConfig
    ) {
        parent::__construct($presentationConfig, $imageParamsBuilder, $viewAssetImageFactory, $placeholderFactory);
        $this->scopeConfig = $scopeConfig;
    }

    /**
     * @param string $baseFilePath
     * @param string $imageDisplayArea
     * @return string
     */
    public function getUrl(string $baseFilePath, string $imageDisplayArea): string
    {

        if($imageDisplayArea !== 'product_page_image_large'){
            return  parent::getUrl($baseFilePath, $imageDisplayArea);
        }

        if (!$this->scopeConfig->getValue(self::XML_WEB_REFILO_CDN_REFILO_STOREFRONT_CDN_URL)) {
            return  parent::getUrl($baseFilePath, $imageDisplayArea);
        }

        // TODO: check and just logic
        return $this->scopeConfig->getValue(self::XML_WEB_REFILO_CDN_REFILO_STOREFRONT_CDN_URL) . $baseFilePath;
    }
}
