<?php

namespace App\Listener;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;

/**
 * Class AfterLoginRedirection
 *
 * @package App\AppListener
 */
class AfterLoginRedirection implements AuthenticationSuccessHandlerInterface
{
    private $router;

    /**
     * AfterLoginRedirection constructor.
     *
     * @param RouterInterface $router
     */
    public function __construct(RouterInterface $router)
    {
        $this->router = $router;
    }

    /**
     * @param Request        $request
     *
     * @param TokenInterface $token
     *
     * @return RedirectResponse
     */
    public function onAuthenticationSuccess(Request $request, TokenInterface $token)
    {
        $roles = $token->getRoles();

        $rolesTab = array_map(function ($role) {
            return $role->getRole();
        }, $roles);

        if ($request->getSession()->has('_groupId') && !$token->getUser()->getGroups()->containsKey($request->getSession()->get('_groupId'))) {
            $request->getSession()->remove('_groupId');
        }
        if (!$request->getSession()->has('_groupId') && count($token->getUser()->getGroups()) > 1) {
            $request->getSession()->set('_choixGroup', 'true');
        }

        if (in_array('ROLE_SUPER_ADMIN', $rolesTab, true)) {
            // c'est un administrateur
            if ($this->getTargetUrlFromSession($request->getSession(), $token) != null) {
                // on le redirige vers l'url demandée à l'origine si elle existe
                $redirection = new RedirectResponse($this->getTargetUrlFromSession($request->getSession(), $token));
            } else {
                // sinon on le redirige vers le dashboard
                $redirection = new RedirectResponse($this->router->generate('sonata_admin_dashboard'));
            }
        } else {
            $redirection = new RedirectResponse($this->router->generate('index'));
        }

        return $redirection;
    }

    /**
     * @return string|null
     */
    private function getTargetUrlFromSession(SessionInterface $session, TokenInterface $token)
    {
        $key = sprintf('_security.%s.target_path', $token->getProviderKey());

        if ($session->has($key)) {
            return $session->get($key);
        }

        return null;
    }
}
