<?php

namespace App\EventListener;

use App\Entity\Usergroup;
use FOS\UserBundle\Model\UserInterface;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;

//https://redmine.coopdev.fr/issues/4878
//Fill session again after remember_me login
//https://stackoverflow.com/questions/7995366/how-can-i-listen-for-remember-me-reauthentication-events-in-symfony2
//https://rihards.com/2018/symfony-login-event-listener/

class LoginListener
{
    private $session;

    public function __construct(SessionInterface $session)
    {
        $this->session = $session;
    }

    public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
    {
        $tokenName = (string) $event->getAuthenticationToken();
        if(strpos($tokenName,"RememberMeToken") !== false) {
            $user = $event->getAuthenticationToken()->getUser();
            if ($user->getGroups()->count() > 0) {
                $groupe = $user->getGroups()->first();
                $this->updateSessionGroup($user, $groupe);
            }
        }
    }

    private function updateSessionGroup(UserInterface $user, Usergroup $groupe)
    {
        if (in_array('ROLE_PRESTATAIRE', $groupe->getRoles()) && count($user->getPrestataires()) >= 1) {
            $this->session->set('_prestagere', $user->getPrestataires()[0]);
        } elseif (in_array('ROLE_CAISSIER', $groupe->getRoles()) && count($user->getCaissiers()) >= 1) {
            $this->session->set('_prestagere', $user->getCaissiers()[0]->getPrestataire());
        } elseif (in_array('ROLE_COMPTOIR', $groupe->getRoles()) && count($user->getComptoirsGeres()) >= 1) {
            $this->session->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) {
            $this->session->set('_groupegere', $user->getGroupesGeres()[0]);
        }
    }
}
