<?php

namespace KupShop\ComponentsBundle\EventListener;

use KupShop\ComponentsBundle\Interfaces\Microdata;
use KupShop\ComponentsBundle\Twig\DataProvider\MicrodataProvider;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\UX\TwigComponent\Event\PostRenderEvent;

class PostRenderListener implements EventSubscriberInterface
{
    public function __construct(protected MicrodataProvider $microDataProvider)
    {
    }

    public static function getSubscribedEvents(): array
    {
        return [
            PostRenderEvent::class => [
                ['processMicroData', 100],
            ],
        ];
    }

    public function processMicroData(PostRenderEvent $event)
    {
        // Funkce zkontroluje jestli ma komponenta aktivovany mikrodata - interface
        // Nasledne zkontroluje jestli mikrodata co se vraci z komponenty jsou urceny pro tento scope
        if (in_array(Microdata::class, class_implements($event->getMountedComponent()->getComponent()))) {
            if (!$this->microDataProvider->getActiveScope()) {
                return;
            }
            $microdata = $event->getMountedComponent()->getComponent()->initMicroData();
            // Z mikrodat ktery vraci komponenta si vytahnu jestli jsou pro aktivni scope
            if (array_key_first($microdata) == $this->microDataProvider->getActiveScope()) {
                $this->microDataProvider->appendData($microdata);
            }

            if ($this->microDataProvider->getActiveScope() == $event->getMountedComponent()->getComponent()::class) {
                $this->microDataProvider->disableActiveScope();
            }
        }
    }
}
