<?php

declare(strict_types=1);

/**
 * @author Amasty Team
 * @copyright Copyright (c) Amasty (https://www.amasty.com)
 * @package Jet Theme Backend for Magento 2 (System)
 */

namespace Amasty\JetTheme\Plugin\Framework\Css\PreProcessor\File;

use Amasty\JetTheme\Model\AssetManager;
use Amasty\JetTheme\Model\TransferConfigProcessor\TransferConfigInterface;
use Magento\Framework\Css\PreProcessor\File\Temporary;

class TemporaryPlugin
{
    /**
     * @var TransferConfigInterface[]
     */
    private $transferConfigProcessors;

    /**
     * @var AssetManager
     */
    private $assetManager;

    public function __construct(
        AssetManager $assetsManager,
        array $transferConfigProcessors
    ) {
        $this->assetManager = $assetsManager;
        $this->transferConfigProcessors = $transferConfigProcessors;
    }

    /**
     * @param Temporary $subject
     * @param string $relativePath
     * @param string $contents
     * @return string[]
     */
    public function beforeCreateFile(Temporary $subject, string $relativePath, string $contents): array
    {
        foreach ($this->transferConfigProcessors as $name => $transferConfigProcessor) {
            if (strpos($relativePath, $transferConfigProcessor->getFileNameToProcess()) !== false) {
                $contents = $this->assetManager->getContent($relativePath, $name, $contents);
                break;
            }
        }

        return [$relativePath, $contents];
    }
}
