<?php

namespace engine\skin\TwigAddons;

#[\Twig\Attribute\YieldReady]
class JsTagNode extends \Twig\Node\Node
{
    public function compile(\Twig\Compiler $compiler) {
        $count = count($this->getNode('params'));

        $compiler->addDebugInfo($this);
        $compiler
            ->raw(PHP_EOL);

        for ($i = 0; ($i < $count); $i++) {
            // argument is not an expression (such as, a \Twig\Node\Textbody)
            // we should trick with output buffering to get a valid argument to pass
            // to the functionToCall() function.
            if (!($this->getNode('params')->getNode($i) instanceof \Twig\Node\Expression\AbstractExpression)) {
                $compiler
                    ->write('ob_start();')
                    ->raw(PHP_EOL);

                $compiler
                    ->subcompile($this->getNode('params')->getNode($i));

                $compiler
                    ->write('$js = ob_get_clean();')
                    ->raw(PHP_EOL);
            }
        }

        $compiler
            // ->write('$context[\'__skin_ref\']->addJS($js);')
            ->write('$this->env->getRuntime(\''.JsTagRuntime::class.'\')->addJS($js);')
            ->raw(PHP_EOL)
            ->write('unset($js);')
            ->raw(PHP_EOL);
    }
}
