<?php

namespace NoahVet\Reef\Subscriber\Symfony;

use NoahVet\Reef\Controller\AbstractController;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class ControllerSubscriber implements EventSubscriberInterface
{
    protected ?AbstractController $controller = null;

    #[\Override]
    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::CONTROLLER => 'onController',
            KernelEvents::RESPONSE => 'onResponse',
        ];
    }

    public function onController(ControllerEvent $event): void
    {
        $controller = $event->getController();

        if (\is_array($controller)) {
            $controller = $controller[0];
        }

        if ($controller instanceof AbstractController) {
            $this->controller = $controller;
            $controller->preInvoke();
        }
    }

    public function onResponse(ResponseEvent $event): void
    {
        if (null === $this->controller) {
            return;
        }

        $this->controller->postInvoke();
        $this->controller = null;
    }
}
