<?php

declare(strict_types=1);

namespace FiloBlu\Refilo\Plugins;

use Magento\Framework\App\ProductMetadataInterface;
use Magento\Framework\Filesystem\DirectoryList;
use Magento\Framework\Filesystem\DriverInterface;
use Magento\PageBuilder\Model\Config\FileResolver;

/**
 *
 */
class RemovePagePuilderUnsupportedTags
{
    /**
     * @var \Magento\Framework\Filesystem\DriverInterface
     */
    private $driver;
    /**
     * @var \Magento\Framework\Filesystem\DirectoryList
     */
    private $directoryList;
    /**
     * @var \Magento\Framework\App\ProductMetadataInterface
     */
    private $productMetadata;

    /**
     * @param \Magento\Framework\Filesystem\DirectoryList $directoryList
     * @param \Magento\Framework\Filesystem\DriverInterface $driver
     * @param \Magento\Framework\App\ProductMetadataInterface $productMetadata
     */
    public function __construct(
        DirectoryList $directoryList,
        DriverInterface $driver,
        ProductMetadataInterface $productMetadata
    ) {
        $this->driver = $driver;
        $this->directoryList = $directoryList;
        $this->productMetadata = $productMetadata;
    }

    /**
     * @return void
     * @see \Magento\PageBuilder\Model\Config\FileResolver::get()
     */
    public function afterGet(FileResolver $subject, array $result): array
    {
        $result = $this->removeBreakpoints($result);
        return $result;
    }

    /**
     * @param array $result
     * @return array
     */
    public function removeBreakpoints(array $result): array
    {
        $version = $this->productMetadata->getVersion();

        if (version_compare($version, '2.4.1', '>=')) {
            return $result;
        }

        $key = $this->driver->getAbsolutePath(
            $this->directoryList->getRoot() . '/',
            'vendor/filoblu/mod2-refilo/view/adminhtml/pagebuilder/content_type/filoblu_slide.xml'
        );

        if (!isset($result[$key])) {
            return $result;
        }

        $result[$key] = preg_replace('/<breakpoints>.*<\/breakpoints>/s', '', $result[$key]);
        return $result;
    }

}