<?php


namespace AutoAdmin\Bundle\Admin\EventListener;


use AutoAdmin\Bundle\Admin\Configuration\ConfigManager;
use AutoAdmin\Bundle\Admin\Controller\Admin\AbstractAdminController;
use Exception;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Twig\Environment;

class TwigAdminConfigListener
{
    private Environment $twig;
    private ConfigManager $configManager;

    public function __construct(Environment $twig, ConfigManager $configManager)
    {
        $this->twig = $twig;
        $this->configManager = $configManager;
    }

    public function onKernelController(ControllerEvent $event): void
    {
        if (!$this->isSupportedController($event)) {
            return;
        }

        $this->twig->addGlobal('aa_admin_config', $this->configManager->getConfig());
        $this->twig->addGlobal('aa_admin_loader_path', $this->configManager->getConfig('admin_loader_path'));

        // create context variable and assign as global
        $aaContext = [
            'entity' => null,
            'controller' => null,
        ];

        $entitySlug = $event->getRequest()->get('entitySlug');
        if (!empty($entitySlug)) {
            try {
                $entityConfig = $this->configManager->getEntityConfigBySlug($entitySlug);
                $aaContext['entity'] = [
                    'slug' => $entitySlug,
                    'action' => $event->getRequest()->get('action'),
                    'config' => $entityConfig ?? [],
                ];
            } catch (Exception $e) {
            }
        }

        $controllerSlug = $event->getRequest()->get('controllerSlug');
        if (!empty($entitySlug)) {
            try {
                $controllerConfig = $this->configManager->getControllerConfigBySlug($controllerSlug);
                $aaContext['controller'] = [
                    'slug' => $controllerSlug,
                    'method' => $event->getRequest()->get('method'),
                    'config' => $controllerConfig ?? [],
                ];
            } catch (Exception $e) {
            }
        }

        $this->twig->addGlobal('aa', $aaContext);
    }

    private function isSupportedController(ControllerEvent $event): bool
    {
        return is_array($controller = $event->getController())
            && $controller[0] instanceof AbstractAdminController;
    }
}