<?php


namespace AutoAdmin\Bundle\Content\Breadcrumbs\EventListener;


use AutoAdmin\Bundle\Content\Breadcrumbs\BreadcrumbsService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Twig\Environment;

class BreadcrumbsDisplaySubscriber implements EventSubscriberInterface
{
    public function __construct(
        private readonly Environment $twigEnvironment,
        private readonly BreadcrumbsService $breadcrumbsService
    )
    {
    }

    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::RESPONSE => ['onKernelResponse', -42],
        ];
    }

    public function onKernelResponse(ResponseEvent $responseEvent)
    {
        if (!$responseEvent->isMainRequest()) {
            return;
        }

        $request = $responseEvent->getRequest();
        $route = $request->get('_route');

        // todo, here, use content config to know if we have to handle current route
        if (
            $route === null
            || str_starts_with((string) $route, '_')
            || str_starts_with((string) $route, 'aa_admin_')
        ) {
            return;
        }

        $response = $responseEvent->getResponse();
        $content = $response->getContent();
        if (stripos($content, '<!-- <breadcrumbs/> -->') !== false) {
            $response = $this->replaceTag($response);
        }

        return $response;
    }

    private function replaceTag(Response $response): Response
    {
        $breadcrumbsHtml = $this->twigEnvironment->render('/_layout/_breadcrumbs.html.twig', [
            'breadcrumbs'=> $this->breadcrumbsService->compile(),
        ]);
        $content = preg_replace_callback(
            '/(<!-- <breadcrumbs\/> -->)/msu',
            static function (array $matches) use ($breadcrumbsHtml): string {
                $matches[1] = $breadcrumbsHtml;

                return implode('', array_slice($matches, 1));
            },
            $response->getContent()
        );
        $response->setContent($content);

        return $response;
    }
}
