<?php


namespace AutoAdmin\Bundle\Content\Breadcrumbs\EventListener;


use AutoAdmin\Bundle\Content\Breadcrumbs\BreadcrumbsService;
use AutoAdmin\Bundle\Content\Breadcrumbs\Manager\BreadcrumbsGeneratorManagerInterface;
use AutoAdmin\Bundle\Content\Breadcrumbs\Model\BreadcrumbsConfigInterface;
use AutoAdmin\Bundle\Content\Breadcrumbs\Model\BreadcrumbsItem;
use AutoAdmin\Bundle\Content\Event\PostContentMetadataEvent;
use AutoAdmin\Bundle\Content\Routing\ContentRouter;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class BreadcrumbsDataSubscriber implements EventSubscriberInterface
{
    public function __construct(
        private readonly BreadcrumbsService $breadcrumbsService,
        private readonly ContentRouter $contentRouter,
        protected BreadcrumbsGeneratorManagerInterface $breadcrumbsGeneratorManager
    ) {
    }

    public static function getSubscribedEvents(): array
    {
        return [
            PostContentMetadataEvent::class => 'onContentMetadataEvent',
        ];
    }

    public function onContentMetadataEvent(PostContentMetadataEvent $postContentMetadataEvent): void
    {
        $mainContent = $postContentMetadataEvent->getContentContext()->getMainContent();
        if (empty($mainContent)) {
            return;
        }

        if ($mainContent instanceof BreadcrumbsConfigInterface && $mainContent->isHiddenBreadcrumbs() === true) {
//            dump('skipped');
            // we may want to keep the breadcrumbs metadata ?
            return;
        }

        $fragments = $this->breadcrumbsGeneratorManager->generate($mainContent, true);

        // ensure type of all fragments
        foreach ($fragments as $fragment) {
            if (!$fragment instanceof BreadcrumbsItem) {
                $pattern = 'Breadcrumbs fragments must be of type "%s", "%s" type encountered (for main content: %s)';
                throw new \LogicException(
                    sprintf($pattern, BreadcrumbsItem::class, gettype($fragment), get_class($mainContent))
                );
            }
        }

        $items = [];
        /** @var BreadcrumbsItem $fragment */
        foreach ($fragments as $fragment) {
            if ($s = $fragment->getSubject()) {
                $items[] = [
                    'label' => $fragment->getLabel() ?: $s->getCurrentTranslation()->getName(),
                    'url' => $fragment->getUrl() ?: $this->contentRouter->generate($s, 'chain'),
                ];
            } else {
                $items[] = [
                    'label' => $fragment->getLabel(),
                    'url' => $fragment->getUrl(),
                ];
            }
        }

        $items = array_reverse($items);

        /** @var BreadcrumbsItem $item */
        foreach ($items as $idx => $item) {
            $last = $idx === (count($items) - 1);
            $this->breadcrumbsService->add(
                $item['label'],
                $last ? null : $item['url'],
            );
        }
    }
}
