<?php

namespace App\Framework\View\Processors;

use App\Framework\View\ComponentRenderer;
use App\Framework\View\DomComponentService;
use App\Framework\View\DomProcessor;
use App\Framework\View\DomWrapper;
use App\Framework\View\RenderContext;
use Dom\HTMLElement;

/**
 * Erweiterte Version des ComponentProcessors mit DomWrapper-Unterstützung
 */
final readonly class ComponentProcessor implements DomProcessor
{
    public function __construct(
        private DomComponentService $componentService,
        private ComponentRenderer $renderer
    ) {}

    public function process(DomWrapper $dom, RenderContext $context): DomWrapper
    {
        $components = $dom->getElementsByTagName('component');

        $components->forEach(function ($component) use ($context, $dom) {
            /** @var HTMLElement $component */
            $name = $component->getAttribute('name');

            if(!$name) return;

            $attributes = $this->extractAttributes($component);

            $componentHtml = $this->renderer->render($name, array_merge($context->data, $attributes));

            $this->componentService->replaceComponent($dom, $component, $componentHtml);
            #$dom->replaceElementWithHtml($component, $componentHtml);

        });

        return $dom;
    }

    private function extractAttributes(HTMLElement $component): array
    {
        $attributes = [];
        foreach ($component->attributes as $attr) {
            if ($attr->nodeName !== 'name') {
                $attributes[$attr->nodeName] = $attr->nodeValue;
            }
        }
        return $attributes;
    }
}
