<?php

declare(strict_types=1);

namespace KupShop\ComponentsBundle\EventListener;

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

class PreRenderListener implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [
            PreRenderEvent::class => [
                ['setMicroDataScope', 20],
                ['addDataAttributes', 20],
            ],
        ];
    }

    public function __construct(
        protected MicrodataProvider $microDataProvider,
    ) {
    }

    public function addDataAttributes(PreRenderEvent $event)
    {
        /** @var ComponentInterface $component */
        $component = $event->getComponent();

        if (!($event->getComponent() instanceof ComponentInterface)) {
            return;
        }

        $data = [
            'class' => $component->getClassName(),
            'data-component' => $component->shortName,
        ];

        $metadata = $event->getMetadata();
        $variables = $event->getVariables();
        $attributesKey = $metadata->getAttributesVar();

        $variables[$attributesKey] = $variables[$attributesKey]->defaults($data);

        $event->setVariables($variables);
    }

    public function setMicroDataScope(PreRenderEvent $event)
    {
        // Funkce zkontroluje jestli ma komponenta aktivovany mikrodata - interface
        // Nasledne zkontroluje jestli to je komponenta ktera ma svuj scope - pokud ano, aktivuje ho
        if (in_array(Microdata::class, class_implements($event->getComponent()))) {
            if (in_array($event->getComponent()::class, MicrodataProvider::$scopes)) {
                $this->microDataProvider->setActiveScope(MicrodataProvider::$scopes[$event->getComponent()::class]);
            }
        }
    }
}
