<?php


namespace FiloBlu\Refilo\Plugins\Followupemail2;

use Magento\Catalog\Helper\Image as ImageHelper;
use Aheadworks\Followupemail2\Model\Template\Filter;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\View\Asset\Repository as AssetRepository;
use function PHPUnit\Framework\throwException;
use FiloBlu\Refilo\Helper\Data;

class FilterTemplate
{
    /** @var ImageHelper  */
    protected $imageHelper;

    /** @var ProductRepositoryInterface  */
    protected $productRepository;

    /** @var  */
    protected $assetRepository;
    /**
     * @var Data
     */
    protected $refiloHelper;

    public function __construct(
        ImageHelper $imageHelper,
        ProductRepositoryInterface $productRepository,
        AssetRepository $assetRepository,
        Data $refiloHelper
    ){
        $this->imageHelper = $imageHelper;
        $this->productRepository = $productRepository;
        $this->assetRepository = $assetRepository;
        $this->refiloHelper = $refiloHelper;
    }

    /**
     * @param Filter $subject
     * @param $result
     * @return string
     */
    public function afterThumbnailDirective(Filter $subject, $result)
    {
        $path = parse_url($result)['path'];
        $params = explode('/', $path);
        $productId = $params[6];
        $width = $params[8];
        $height = $params[10];

        if (!$productId || !is_numeric($productId)) {
            $productId = $this->findParamValue('product_id', $params);
            $width = $this->findParamValue('width', $params);
            $height = $this->findParamValue('height', $params);
        }

        if ($productId && is_numeric($productId)) {
            try {
                $product = $this->productRepository->getById($productId);

                $this->imageHelper->init(
                    $product,
                    'product_thumbnail_image',
                    [
                        'aspect_ratio'  => true,
                        'width'         => $width,
                        'height'        => $height
                    ]
                );

                return $this->imageHelper->getUrl();
            } catch (NoSuchEntityException $e) {
                throwException($e->getLogMessage());
            }
        }

        $imageUrl = $this->assetRepository->getUrl('spacer.gif');
        return $imageUrl;
    }

    /**
     * @param string $paramName
     * @param $array
     * @return string
     */
    public function findParamValue(string $paramName, $array): string
    {
        if ($paramName == null || $array == null) {
            return '';
        }

        if (!$identifierPosition = array_search($paramName, $array)) {
            return '';
        }

        return $array[++$identifierPosition] ?? '';
    }

}
