<?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();

        $mainContentClass = is_null($mainContent) ? null : $mainContent::class;

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

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

        $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),
                ];
            } 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'],
            );
        }
    }
}
