<?php declare(strict_types = 1);

namespace idoit\Module\SyneticsFlows\Template\DataVisitor;

use Twig\Environment;
use Twig\Node\Expression\ConstantExpression;
use Twig\Node\Expression\FilterExpression;
use Twig\Node\Expression\GetAttrExpression;
use Twig\Node\Node;
use Twig\NodeVisitor\NodeVisitorInterface;

class DataVisitor implements NodeVisitorInterface
{

    public function enterNode(Node $node, Environment $env): Node
    {
        if (!$node instanceof FilterExpression) {
            return $node;
        }

        $base = $node->getNode('node');
        $filter = $node->getNode('filter');

        if (!$filter->hasAttribute('value') || $filter->getAttribute('value') !== 'data') {
            return $node;
        }
        $arguments = $node->getNode('arguments');
        $nodes = [];
        foreach ($arguments as $argument) {
            $nodes[] = $argument;
        }

        $path = $this->getPath($base);
        if (!empty($path)) {
            $nodes[] = new ConstantExpression(join('.', $path), $node->getTemplateLine());
        }
        $node->setNode('arguments', new Node($nodes));
        return $node;
    }

    private function getPath(Node $node): array
    {
        if (!$node instanceof GetAttrExpression) {
            return [];
        }
        $parent = $node->getNode('node');
        $value = $node->getNode('attribute')->getAttribute('value');
        return [...$this->getPath($parent), $value];
    }

    public function leaveNode(Node $node, Environment $env): ?Node
    {
        return $node;
    }

    public function getPriority()
    {
        return 0;
    }
}