<?php
namespace App\EventListener;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Http\Event\SwitchUserEvent;
use Symfony\Component\Security\Http\SecurityEvents;

class SwitchUserSubscriber implements EventSubscriberInterface
{
    private $router;

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

    public function onSwitchUser(SwitchUserEvent $event)
    {
        $request = $event->getRequest();
        $token = $event->getToken();
        $user = $event->getTargetUser();

        $request->getSession()->remove('_prestagere');
        $request->getSession()->remove('_comptoirgere');
        $request->getSession()->remove('_groupegere');
        if ($request->hasSession() && $request->getSession()->has('_groupId') &&
         !$user->getGroups()->contains($request->getSession()->get('_groupId'))) {
            $request->getSession()->remove('_groupId');
        }
        if (!$request->getSession()->has('_groupId')) {
            if (count($user->getGroups()) > 1) {
                $request->getSession()->set('_choixGroup', 'true');
            } else {
                $request->getSession()->set('_groupId', $user->getGroups()[0]);
                foreach ($user->getGroups() as $groupe) {
                    if (in_array('ROLE_SUPER_ADMIN', $groupe->getRoles())) {
                        $request->getSession()->remove('_choixGroup');
                    }
                    if (in_array('ROLE_PRESTATAIRE', $groupe->getRoles()) && count($user->getPrestataires()) >= 1) {
                        $request->getSession()->set('_prestagere', $user->getPrestataires()[0]);
                    } elseif (in_array('ROLE_COMPTOIR', $groupe->getRoles()) && count($user->getComptoirsGeres()) >= 1) {
                        $request->getSession()->set('_comptoirgere', $user->getComptoirsGeres()[0]);
                    } elseif ((in_array('ROLE_TRESORIER', $groupe->getRoles()) || in_array('ROLE_CONTACT', $groupe->getRoles()) || in_array('ROLE_GESTION_GROUPE', $groupe->getRoles())) && count($user->getGroupesGeres()) >= 1) {
                        $request->getSession()->set('_groupegere', $user->getGroupesGeres()[0]);
                    }
                }
            }
        }
    }

    public static function getSubscribedEvents()
    {
        return [
            // constant for security.switch_user
            SecurityEvents::SWITCH_USER => 'onSwitchUser',
        ];
    }
}
