<?php

declare(strict_types=1);

namespace App\Framework\View\Processors;

use App\Framework\Template\Processing\DomProcessor;
use App\Framework\View\DomWrapper;
use App\Framework\View\RenderContext;
use Dom\Element;

# Ersetzt ein eigenes `<switch value="foo">` mit inneren `<case when="bar">`-Elementen.

final readonly class SwitchCaseProcessor implements DomProcessor
{
    /**
     * @inheritDoc
     */
    public function process(DomWrapper $dom, RenderContext $context): DomWrapper
    {
        foreach ($dom->querySelectorAll('switch[value]') as $switchNode) {
            $key = $switchNode->getAttribute('value');
            $value = $context->data[$key] ?? null;

            $matchingCase = null;
            $defaultCase = null;

            foreach ($switchNode->childNodes as $child) {
                if (! ($child instanceof Element)) {
                    continue;
                }

                if ($child->tagName === 'case') {
                    $caseValue = $child->getAttribute('value');
                    if ((string)$value === $caseValue) {
                        $matchingCase = $child;

                        break;
                    }
                }

                if ($child->tagName === 'default') {
                    $defaultCase = $child;
                }
            }

            $replacement = $dom->createDocumentFragment();

            if ($matchingCase) {
                foreach ($matchingCase->childNodes as $child) {
                    $replacement->appendChild($child->cloneNode(true));
                }
            } elseif ($defaultCase) {
                foreach ($defaultCase->childNodes as $child) {
                    $replacement->appendChild($child->cloneNode(true));
                }
            }

            $switchNode->parentNode?->replaceChild($replacement, $switchNode);
        }

        return $dom;
    }
}
