<?php declare(strict_types=1);

namespace Newland\ToubizWidgetRendering\Renderer;

use Neos\Flow\Annotations as Flow;
use Neos\Flow\Configuration\Exception\InvalidConfigurationException;
use Neos\Flow\ResourceManagement\ResourceManager;
use Newland\ToubizWidgetRendering\Utility\HtmlUtility;
use Newland\ToubizWidgetRendering\Utility\ValidationUtility;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Renderer that renders the widget based on a pre-compiled client-only
 * script. This is meant as a fallback, for when
 * - Server side rendering is not possible
 * - Customized client side rendering is not configurred
 *
 * It will render the detail page but without the customizations of pointing it
 * to a custom `tailwind.config.js`
 */
class PrecompiledClientRenderer implements ToubizWidgetRenderer
{
    /**
     * @var ResourceManager
     * @Flow\Inject()
     */
    protected $resourceManager;

    /**
     * @var ValidationUtility
     * @Flow\Inject()
     */
    protected $validation;

    /**
     * @var HtmlUtility
     * @Flow\Inject
     */
    protected $html;

    /** @var array */
    protected $configuration;

    public function setConfiguration(array $configuration): void
    {
        $this->validation->throwIfReferencedFilesDoNotExist($configuration, [ 'entry' ]);
        $this->configuration = $configuration;
    }

    public function render(string $tagName, array $arguments): string
    {
        $scriptUrl = $this->resourceManager->getPublicPackageResourceUriByPath($this->configuration['entry']);

        return $this->html->siblings([
            $this->html->build('div', [ 'data-toubiz-widget-rendering' => '' ], [
                $this->html->buildVue('tb-component-library-wrapper', [], [
                    $this->html->buildVue($tagName, $arguments)
                ])
            ]),
            $this->html->build('script', [ 'src' => $scriptUrl ]),
        ]);
    }

    public function precompile(OutputInterface $output): void
    {
        $output->writeln('Nothing to do');
    }
}
