<?php

namespace App\Listener;

use App\Entity\Usergroup;
use Doctrine\ORM\EntityManagerInterface;
use FOS\UserBundle\Model\UserInterface;
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\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;

/**
 * Class AfterLoginRedirection.
 */
class AfterLoginRedirection implements AuthenticationSuccessHandlerInterface
{
    private $router;
    private $em;
    private $tokenStorage;
    private $session;

    /**
     * AfterLoginRedirection constructor.
     *
     * @param RouterInterface $router
     */
    public function __construct(RouterInterface $router, EntityManagerInterface $em, TokenStorageInterface $tokenStorage, SessionInterface $session)
    {
        $this->router = $router;
        $this->em = $em;
        $this->tokenStorage = $tokenStorage;
        $this->session = $session;
    }

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

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

        $request->getSession()->remove('_prestagere');
        $request->getSession()->remove('_comptoirgere');
        $request->getSession()->remove('_groupegere');
        if (1 == $user->getPossiblegroups()->count()) {
            if (1 != $user->getGroups()->count()) {
                $groupe = $user->getPossiblegroups()->first();
                $this->updateSessionGroup($user, $groupe);
                $user->setGroups([$groupe]);
                $this->em->persist($user);
                $this->em->flush();
                $this->updateToken($user);
            } else {
                $groupe = $user->getGroups()->first();
                $this->updateSessionGroup($user, $groupe);
            }
        } elseif (count($user->getPossiblegroups()) > 1) {
            if (1 != $user->getGroups()->count()) {
                $hasSuperAdminRole = false;
                foreach ($user->getPossiblegroups() as $groupe) {
                    if (in_array('ROLE_SUPER_ADMIN', $groupe->getRoles())) {
                        $hasSuperAdminRole = true;
                        $user->setGroups([]);
                        $this->em->persist($user);
                        $this->em->flush();
                        $this->em->refresh($user);
                        $user->setGroups([$groupe]);
                        $this->em->persist($user);
                        $this->em->flush();
                        $this->updateToken($user);
                    }
                }
                if (!$hasSuperAdminRole) {
                    $user->setGroups([]);
                    $this->em->persist($user);
                    $this->em->flush();
                    $this->updateToken($user);
                }
            } else {
                $groupe = $user->getGroups()->first();
                $this->updateSessionGroup($user, $groupe);
            }
        }

        if (in_array('ROLE_SUPER_ADMIN', $rolesTab, true)) {
            // c'est un administrateur
            $redirection = new RedirectResponse($this->router->generate('sonata_admin_dashboard'));
        } else {
            $redirection = new RedirectResponse($this->router->generate('index'));
        }

        return $redirection;
    }

    private function updateToken($user)
    {
        $grp = $user->getGroups() ? $user->getGroups()[0] : null;
        $token = new UsernamePasswordToken($user, $user->getPassword(), 'main', $grp ? $grp->getRoles() : ['ROLE_USER']);
        $this->tokenStorage->setToken($token);
    }

    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]);
        } 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]);
        }
    }
}
