<?php

namespace App\EventListener;


use App\Entity\User;
use App\Repository\UserTypeRepository;
use Doctrine\ORM\EntityManager;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Symfony\Component\Security\Core\Authentication\Token\Storage\UsageTrackingTokenStorage;

class ControllerListener
{
    private $router;
    private $tokenStorage;
    private $em;

    /**
     * ControllerListener constructor.
     * @param RouterInterface $router
     * @param TokenStorage $tokenStorage
     * @param EntityManager $em
     */
    public function __construct(RouterInterface $router, UsageTrackingTokenStorage $tokenStorage, EntityManager $em)
    {
        $this->router = $router;
        $this->tokenStorage = $tokenStorage;
        $this->em = $em;
    }

    public function onKernelRequest(RequestEvent $event)
    {
        $request = $event->getRequest();
        $route = $request->attributes->get('_route');

        if ($this->tokenStorage->getToken() !== null) {
            /** @var User $user */
            $user = $this->tokenStorage->getToken()->getUser();
            $isNormalUser = $user !== 'anon.' && $user->getUserType()->getType() === UserTypeRepository::USER_TYPE_USER;

            if ($isNormalUser && $route !== null && $route !== 'legal_page' && $route !== 'accept_legal_terms') {

                if (!$user->getAcceptedLegal() || !$user->getAcceptedTerms()) {
                    $url = $this->router->generate('legal_page');
                    $response = new RedirectResponse($url);
                    $event->setResponse($response);
                }
            }
        }
    }

    public function onKernelException(ExceptionEvent $event)
    {
        
    }
}