<?php

namespace AppBundle\Security;

use AppBundle\Entity\Utilisateur;
use DateTime;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\DependencyInjection\ContainerInterface as Container;
use Symfony\Component\Routing\RouterInterface;

class SecurityService
{
    private $em;
    private $container;
    private $router;


    /**
     * SecurityService constructor.
     * @param EntityManagerInterface $em
     * @param Container $container
     * @param RouterInterface $router
     */
    public function __construct(EntityManagerInterface $em, Container $container, RouterInterface $router)
    {
        $this->em = $em;
        $this->container = $container;
        $this->router = $router;
    }

    public function checkBan(GetResponseEvent $event)
    {
        /** @var Utilisateur $user */
        $token = $this->container->get('security.token_storage')->getToken();
        $user = $token ? $token->getUser() : null;


        if ($user and $user != "anon." and $user->getDateFinBanDT() > new DateTime()) {
            $this->container->get('session')->getFlashBag()->add('error', $this->container->get('translator')->trans('YOU_ARE_BANNED'));

            $response = new RedirectResponse($this->router->generate('security_logout'));
            $event->setResponse($response);
        }
    }

}