<?php

namespace App\EventSubscriber;

use App\Entity\User;
use Twig\Environment;
use Doctrine\ORM\EntityManagerInterface;
use App\Repository\NotificationRepository;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

class NotificationsSubscriber implements EventSubscriberInterface
{
    private Environment $twig;
    private TokenStorageInterface $tokenStorage;
    private EntityManagerInterface $entityManager;

    public function __construct(
        Environment $twig,
        TokenStorageInterface $tokenStorage = null,
        EntityManagerInterface $entityManager
    ) {
        $this->twig = $twig;
        $this->tokenStorage = $tokenStorage;
        $this->entityManager = $entityManager;
    }

    public function onKernelController(ControllerEvent $event)
    {
        if (null === $this->tokenStorage) {
            return;
        }

        $token = $this->tokenStorage->getToken();

        if (null === $token) {
            return;
        }

        /**
         * @var NotificationRepository notificationRepo
         */

        if (null === ($notificationRepo = $this->entityManager->getRepository("App:Notification"))) {
            return;
        }

        /**
         * @var User $User
         */
        $User = $token->getUser();

        if (null === $User) {
            return;
        }

        $this->twig->addGlobal(
            'user_notifications_list',
            $notificationRepo->listForUser($User)
             ->readed(false)
             ->limit(5)
             ->order(['createdAt' => 'DESC'])
             ->getResult()
        );

        $this->twig->addGlobal(
            'user_notifications_count',
            $notificationRepo->listForUser($User)
             ->readed(false)
             ->limit(5)
             ->order(['createdAt' => 'DESC'])
             ->getCount()
        );
    }

    public static function getSubscribedEvents()
    {
        return [
            'kernel.controller' => 'onKernelController',
        ];
    }
}
