<?php

namespace App\EventListener;

use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\FilterUserResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\HttpFoundation\RequestStack;

class PreventDisabledUserAutoLoginListener implements EventSubscriberInterface
{
    private $tokenStorage;
    private $requestStack;

    public function __construct(TokenStorageInterface $tokenStorage, RequestStack $requestStack)
    {
        $this->tokenStorage = $tokenStorage;
        $this->requestStack = $requestStack;
    }

    public static function getSubscribedEvents()
    {
        return [
            FOSUserEvents::RESETTING_RESET_COMPLETED => ['onResettingCompleted', 999], // high priority
        ];
    }

    public function onResettingCompleted(FilterUserResponseEvent $event)
    {
        $user = $event->getUser();

        if (!$user->isEnabled()) {
            // Add flash message before deleting token
            $request = $this->requestStack->getCurrentRequest();
            if ($request) {
                $request->getSession()->getFlashBag()->add('success', 'Votre mot de passe a été modifié. Vous pourrez vous connecter lorsque votre compte sera activé.');
            }

            // Delete authentication token so disabled user isn't automaticaly connected after resetting password
            $this->tokenStorage->setToken(null);
        }
    }
}